你好
我正在将redux与react-native一起使用,到目前为止很棒!
在我的应用程序中,我有用户个人资料,状态如下:
{
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
作为道具传递了loadUser
动作。
这会向API发出请求,并将用户响应添加到我的users
状态。
现在,我希望我的Profile组件能够接收用户作为道具进行渲染。
所以基本上我想做这样的事情:
function mapStateToProps(state) {
return {
user: state.users[props.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
显然这是行不通的,因为我无法使用道具。
我无法使用selectedProfile
进行过滤,因为我正在导航堆栈中呈现多个配置文件,每个配置文件都有不同的userId,如果使用全局selectedProfile状态,则会破坏后退按钮。
我发现的唯一解决方法是创建一个ProfileContainer
组件,该组件将通过其属性过滤状态并将单个用户传递给Profile
组件。
class ProfileContainer extends React.Component {
render() {
let user = this.props.users[this.prop.userId];
return <Profile user={user} />
}
}
是否有意义? 还有其他人遇到这个问题吗?
谢谢,
然
嘿,
这更多是一个react-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中提交此类问题。
它与此存储库无关。
最有用的评论
嘿,
这更多是一个react-redux问题...我可能会丢失一些东西,但对我来说似乎很简单,请使用传递给mapStateToProps的“ ownProps”参数,因此上面的代码将如下所示:
您绝对可以访问组件的道具。 看起来如何? 有关更多详细信息,请参见https://github.com/rackt/react-redux#connectmapstatetoprops -mapdispatchtoprops-mergeprops-options或https://github.com/rackt/redux/blob/master/examples/real-world/containers/真实示例的