μλ νμΈμ,
λλ λ°μ λ€μ΄ν°λΈμ ν¨κ» reduxλ₯Ό μ¬μ©νκ³ μμΌλ©° μ§κΈκΉμ§ νλ₯ν©λλ€!
λ΄ μ±μλ μ¬μ©μ νλ‘νμ΄ μμΌλ©° μνλ λ€μκ³Ό κ°μ΅λλ€.
{
users: {
"1": {id: "1", name: "Ran"},
"2": {id: "2", name: "Dan"}
}
}
μ΄μ λ¨μΌ μ¬μ©μλ₯Ό λ λλ§νλ <Profile>
κ΅¬μ± μμκ° μμ΅λλ€.
class Profile extends React.Component {
componentDidMount() {
const { dispatch, userId } = this.props;
dispatch(loadUser(userId));
}
render() {
console.log(this.props.user.name);
}
}
κ΅¬μ± μμκ° λ§μ΄νΈλλ©΄ userId
λ₯Ό propμΌλ‘ μ λ¬νμ¬ loadUser
μμ
μ μ λ¬ν©λλ€.
κ·Έλ¬λ©΄ APIμ λν μμ²μ΄ μμ±λκ³ μ¬μ©μ μλ΅μ΄ λ΄ users
μνμ μΆκ°λ©λλ€.
μ΄μ λ΄ νλ‘ν κ΅¬μ± μμκ° μ¬μ©μκ° μνμΌλ‘ λ λλ§νλλ‘ λ°κΈ°λ₯Ό μν©λλ€.
κ·Έλμ κΈ°λ³Έμ μΌλ‘ λ€μκ³Ό κ°μ΄νκ³ μΆμ΅λλ€.
function mapStateToProps(state) {
return {
user: state.users[props.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
μνμ λν μ‘μΈμ€ κΆνμ΄ μκΈ° λλ¬Έμ λΆλͺ
ν μλνμ§ μμ΅λλ€.
λ΄ νμ μ€νμμ μ¬λ¬ νλ‘νμ λ λλ§νκΈ° λλ¬Έμ selectedProfile
μ κ°μ μνλ₯Ό μ¬μ©νμ¬ νν°λ§ ν μ μμ΅λλ€. κ° νλ‘νμ μλ‘ λ€λ₯Έ userIdλ₯Ό κ°μ§κ³ μμ΅λλ€. global selectedProfile μνλ₯Ό μ¬μ©νλ©΄ λ€λ‘ λ²νΌμ΄ κΉ¨μ§λλ€.
λ΄κ° μ°Ύμ μ μΌν ν΄κ²° λ°©λ²μ ProfileContainer
κ΅¬μ± μμλ₯Ό λ§λλ κ²μ
λλ€.μ΄ κ΅¬μ± μμλ ν΄λΉ propμΌλ‘ μνλ₯Ό νν°λ§νκ³ λ¨μΌ μ¬μ©μλ₯Ό Profile
κ΅¬μ± μμμ μ λ¬ν©λλ€.
class ProfileContainer extends React.Component {
render() {
let user = this.props.users[this.prop.userId];
return <Profile user={user} />
}
}
λ§μ΄ λλμ? λ€λ₯Έ μ¬λμ΄μ΄ λ¬Έμ κ° λ°μν©λκΉ?
κ°μ¬,
λ.
μΌ,
μ΄κ²μ λ λ§μ λ°μ -redux λ¬Έμ μ λλ€ ... λκ° λΉ μ‘μ μλ μμ§λ§, μ μκ²λ λ§€μ° κ°λ¨ ν΄ λ³΄μ λλ€. mapStateToPropsμ μ λ¬λλ "ownProps"μΈμλ₯Ό μ¬μ©νλ©΄ μμ μ½λκ° λ€μκ³Ό κ°μ΄ λ³΄μΌ κ²μ λλ€.
function mapStateToProps(state, ownProps) {
return {
user: state.users[ownProps.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
κ΅¬μ± μμμ μνμ νμ€ν μ‘μΈμ€ ν μ μμ΅λλ€. μ΄λ»κ² 보μ λκΉ? μμΈν λ΄μ©μ https://github.com/rackt/react-redux#connectmapstatetoprops -mapdispatchtoprops-mergeprops-options λλ https://github.com/rackt/redux/blob/master/examples/real-world/containers/λ₯Ό μ°Έμ‘°νμμμ€. μ€μ μμ λ₯Όμν
λ΄κ° κ·Έκ²μ λμ³€λ€λ κ²μ λ―Ώμ μ μμ΅λλ€! κ°μ¬ν©λλ€ @alanrubin
: μ’μμ :
ν₯ν react-redux μ μ΄λ¬ν λ¬Έμ λ₯Ό μ μΆνμμμ€.
μ΄ μ μ₯μμ κ΄λ ¨μ΄ μμ΅λλ€.
κ°μ₯ μ μ©ν λκΈ
μΌ,
μ΄κ²μ λ λ§μ λ°μ -redux λ¬Έμ μ λλ€ ... λκ° λΉ μ‘μ μλ μμ§λ§, μ μκ²λ λ§€μ° κ°λ¨ ν΄ λ³΄μ λλ€. mapStateToPropsμ μ λ¬λλ "ownProps"μΈμλ₯Ό μ¬μ©νλ©΄ μμ μ½λκ° λ€μκ³Ό κ°μ΄ λ³΄μΌ κ²μ λλ€.
κ΅¬μ± μμμ μνμ νμ€ν μ‘μΈμ€ ν μ μμ΅λλ€. μ΄λ»κ² 보μ λκΉ? μμΈν λ΄μ©μ https://github.com/rackt/react-redux#connectmapstatetoprops -mapdispatchtoprops-mergeprops-options λλ https://github.com/rackt/redux/blob/master/examples/real-world/containers/λ₯Ό μ°Έμ‘°νμμμ€. μ€μ μμ λ₯Όμν