使用react,redux和immer更新状态时,组件不会重新渲染

时间:2020-03-18 13:49:22

标签: javascript reactjs redux react-redux immer.js

我有一个简单的代码,其中包含一个用于显示提要的PostFeed组件和一个用于显示每个提要的PostItem组件。在PostItem中,用户可以执行供稿,并且这里的服务调用和许多赞将更改。如果当前用户喜欢该供稿,则拇指将为蓝色。

刷新页面后,一切都很好,但是当提要变得喜欢或不喜欢时,状态会更新,并且真正喜欢的次数会发生改变,但组件的颜色不会改变。 为了防止不可变,我使用了 Immer

这是代码

//PostFeed Component
class PostFeed extends Component {
  render() {
    const { posts } = this.props;

    return posts && posts.map(post => <PostItem key={post._id} post={post} />);
  }
}

//PostItem Component
class PostItem extends Component {

  componentWillReceiveProps(nextProps) {
    if (nextProps.post) {
      this.setState({ post: nextProps.post });
        }
      }

  onLikeClick(id) {
    this.props.addLike(id);
  }

  isCurrentUserLike(likes: ILike[]) {
    const { auth } = this.props;
    if (likes.filter(like => like.user === (auth.user as any).id).length > 0) {
      return <i className="fas fa-thumbs-up text-info" />;
    } else {
      return <i className="fas fa-thumbs-up" />;
    }
  }

render() {
const { post, auth } = this.props;
return (
      <div className="card card-body mb-3">

...

<button onClick={this.onLikeClick.bind(this, post._id)} type="button" className="btn btn-light mr-1">

        // This line does not re-render                 
        {this.isCurrentUserLike(post.likes)}

       <span className="badge badge-light">{post.likes.length}</span>
    </button>
      }
    }

const mapStateToProps = (state) => ({
  auth: state.auth
});

export default connect(mapStateToProps, { addLike})(
  PostItem
);

这是活动:

export const addLike = (id) => (dispatch) => {
  axios
    .post(`/api/posts/like/${id}`)
    .then(res =>
      dispatch({
        type: "POST_LIKED",
        payload: res.data
      })
    )
    .catch(err =>
      dispatch({
        type: "GET_ERRORS",
        payload: err.response.data
      })
    );
};

这是减速器:

export default (state = initialState, action) => {
  return produce(state, (draft): any => {
    switch (action.type) {

 case "POST_LIKED":
        draft.posts = substitudePost(draft.posts, action.payload);
        draft.loading = false;
        break;
}}
    )}

const substitudePost = (posts, post) => {
  const index = posts.findIndex(i => i._id == post._id);
  if (index > -1) posts[index] = post;
  return posts;
}

这些是数据类型:

 interface initialFeedState= {
  posts: IPost[],
  post: IPost,
  loading: false
};

interface IPost  {
  _id: string;
  user: IUser;
  likes: ILike[];
  comments: IComment[];
  date: string;
}

1 个答案:

答案 0 :(得分:0)

我认为问题出在这行

if (likes.filter(like => like.user === (auth.user as any).id).length > 0) {

您正在将用户对象与经过身份验证的用户 id 进行比较,它们永远不会相同。您可以使用这样的一些功能

if (likes.some(like => like.user.id === auth.user.id)) {
相关问题