I am trying to filter a set of objects in the state whenever the user clicks on a button on my component.(每当用户单击组件上的按钮时,我都试图过滤状态下的一组对象。)
The logic of the filtering works fine, but when it gets back to the component, the filtered objects are missing and instead the property is undefined.(过滤的逻辑工作正常,但是当返回到组件时,过滤的对象会丢失,而属性是未定义的。) Am I missing a lifecycle method?(我是否缺少生命周期方法?)
The click event:(点击事件:)
<div onClick={this.filterMyPosts}>My Posts</div>
...
<div>
{this.renderPosts()}
</div>
filterMyPosts(filterMyPosts)
filterMyPosts() {
this.props.updateFilter("myPosts");
// filtering function uses switch statement based on strings to filter posts
}
The component container:(组件容器:)
const mapStateToProps = (state) => {
return {currentUser: state.session.currentUser,
posts: allPostsByFilter(state.posts, state.filter, state.session.currentUser.id, state.bookmarks)}
};
const mapDispatchToProps = (dispatch) => ({
updateFilter: (filter) => dispatch(updateFilter(filter))
})
The filtering takes place in a different file, which returns the filtered events in an object.(筛选发生在另一个文件中,该文件返回对象中已筛选的事件。) That logic has no errors.(该逻辑没有错误。)
The problem : By the time it gets to the following function, "posts" is undefined.(问题 :到以下功能时,“ posts”尚未定义。) So somewhere along the way, the filtered posts are not making it back to the component.(因此,在此过程中的某个地方,过滤后的帖子不会将其放回到组件中。)
renderPosts() {
return (
<div className ="user-profile-posts">
<ul>
{Object.keys(this.props.posts).map(id => <PostIndexItem
key={`posts-index-item${id}`}
post={this.props.posts[id]}
user={true}
/>)}
</ul>
</div>
);
}
EDIT - filter function(编辑-过滤功能)
export const allPostsByFilter = (filter, currentUserId, posts) => {
switch (filter) {
case "myPosts":
let postKeys = Object.keys(posts).filter( (id) => {
return(posts[id].user_id === currentUserId)
});
let userPosts = {}
postKeys.forEach( (key) => userPosts[key] = posts[key])
let newPosts = {}
let postKeys = Object.keys(posts).filter( (id) => {
return (Object.keys(userPosts).includes(id))
});
eventKeys.forEach( (key) => newPosts[key] = posts[key])
return newPosts
default:
return posts
ask by Marc Fletcher translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…