简体   繁体   中英

Component does not re-render when State is updated using react, redux and immer

I have a simple code which containing a PostFeed component to show feeds and PostItem component inside it which shows each feed. in PostItem user can do like feed and here a service call and a number of likes will change. if the current user has liked the feed, the thumb will have a blue color.

everything works fine when the page refreshed, but when the feed gets to like or dislike, the state gets update and a number of likes changed truly but the component color does not change. In order to prevent Immutableily, I have used Immer .

Here is the code

//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
);

this is acition:

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
      })
    );
};

and this is reducer:

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;
}

and these are Data types:

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

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

I think the problem is on this line

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

You are comparing the user object with authenticated user id , they will never be the same. And you can use the some function like this

if (likes.some(like => like.user.id === auth.user.id)) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM