我有一个连接到商店的组件,传递到该组件的道具之一是post
,它是一个对象。我想将post.id
传递给mapStateToProps
,以便可以观察对帖子评论数组的更改。
这是我到目前为止尝试过的
const mapStateToProps = state => ({
myProfile: state.users.myProfile,
comments: state.activity.posts[this.postID].comments,
});
const mapStateToProps2 = state => {
const id = this.postID;
return {
myProfile: state.users.myProfile,
comments: state.activity.posts[id].comments,
};
};
有人知道我能做到吗,有什么想法吗?
欢呼
编辑 这是我最后进行的实现:
const mapStateToProps = (state, ownProps) => {
const { navigation } = ownProps;
const navPost = navigation.getParam('post', {});
const postComments = state.activity.posts.filter( post => post.id === navPost.id );
return {
myProfile: state.users.myProfile,
comments: postComments[0].comments,
};
};
答案 0 :(得分:2)
this
关键字很可能引用了错误的范围,并且找不到postId
。
要么在状态中分配ID,然后像state.postId
那样访问它,要么将ID传递给组件的属性,然后像这样使用它:
function mapStateToProps(state, ownProps) {
const { visibilityFilter } = state
const { id } = ownProps
const todo = getTodoById(state, id)
// component receives additionally:
return { todo, visibilityFilter }
}
// Later, in your application, a parent component renders:
;<ConnectedTodo id={123} />
// and your component receives props.id, props.todo, and props.visibilityFilter
来源:https://react-redux.js.org/using-react-redux/connect-mapstate