还原状态的更改不会导致未调用的组件/ componentDidUpdate发生更改

时间:2019-08-04 07:44:06

标签: javascript reactjs redux react-redux

我有一个帖子详细信息组件,其中单击“赞”按钮时,redux状态更改为redux状态,就像

个帖子 -> postDetails

我正在更改postDetais对象的“喜欢”属性和“喜欢”次数,单击“喜欢”按钮后,将“喜欢”属性设置为true(从false设置为true),反之亦然,并且喜欢的数量增加。

但是状态正在改变,但是componentDidUpdate方法没有触发

PostDetails.js

import React, { Component } from "react";
import { connect } from "react-redux";
import {
  getPostData,
  likePost,
  unlikePost
} from "../../store/actions/postsActions";
import { Icon, Tooltip } from "antd";
import { Link } from "react-router-dom";

export class PostDetails extends Component {
  state = {
    postData: this.props.postDetails
  };

  componentDidMount() {
    this.props.getPostData(this.props.match.params.post_id);
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(this.props.postDetails);
    if (prevProps.postDetails !== this.props.postDetails) {
      this.setState({
        postData: this.props.postDetails
      });
    }
  }

  render() {
    const { postData } = this.state;
    const liked = postData.liked;
    return (
      <div className="postDetails">
        {postData && (
          <div className="postDetailsContainer">
            <div className="postImage">
              <img src={postData.imageUrl} alt={postData.caption} />
            </div>
            <div className="postContent">
              <div className="postContent__header">
                <Link
                  to={`/user/${postData.username}`}
                  className="postContent__headerContent"
                >
                  <img
                    src={postData.profileUrl}
                    alt={postData.username}
                    className="postContent__profileImage"
                  />
                  <p className="postContent__username">{postData.username}</p>
                </Link>
              </div>

              <div className="postComments" />
              <div className="postInfo">
                <div className="postActions">
                  {liked ? (
                    <Tooltip title="Unlike post">
                      <Icon
                        type="heart"
                        className="likePost"
                        theme="filled"
                        style={{ color: "#d41c00" }}
                        onClick={() => this.props.unlikePost(postData.id)}
                      />
                    </Tooltip>
                  ) : (
                    <Tooltip title="Like post">
                      <Icon
                        type="heart"
                        className="likePost"
                        onClick={() => this.props.likePost(postData.id)}
                      />
                    </Tooltip>
                  )}
                  <Tooltip title="Comment">
                    <Icon type="message" className="commentButton" />
                  </Tooltip>
                </div>
                <Tooltip title="Refresh comments">
                  <Icon type="reload" className="reloadComments" />
                </Tooltip>
              </div>
              <div />
            </div>
          </div>
        )}
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    postDetails: state.posts.postDetails
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getPostData: postId => dispatch(getPostData(postId)),
    likePost: postId => dispatch(likePost(postId)),
    unlikePost: postId => dispatch(unlikePost(postId))
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PostDetails);

postsReducer.js

const initialState = {
  creatingPost: false,
  feed: [],
  createdPost: false,
  feedUpdated: false,
  postDetails: {}
};

const postsReducer = (state = initialState, action) => {
  switch (action.type) {
    case "CREATING_POST":
      return {
        ...state,
        creatingPost: true,
        createdPost: false
      };
    case "ADD_POST":
      return {
        ...state,
        feed: state.feed.concat(action.payload)
      };
    case "FETCH_FEED":
      return {
        ...state,
        feed: action.payload
      };
    case "CREATED_POST":
      return {
        ...state,
        creatingPost: false,
        createdPost: true
      };
    case "UPDATE_FEED":
      return {
        ...state,
        feed: action.payload,
        feedUpdated: true
      };
    case "GET_POST_DATA":
      return {
        ...state,
        postDetails: action.payload
      };
    case "RESET_FEED_UPDATED":
      return {
        ...state,
        feedUpdated: false
      };
    case "RESET_CREATED_POST":
      return {
        ...state,
        createdPost: false
      };
    case "LIKED_POST":
      const { postDetails } = state;

      postDetails.liked = true;
      postDetails.likes += 1;
      return {
        ...state,
        postDetails: postDetails
      };

    case "UNLIKED_POST":
      const postDetails1 = state.postDetails;

      postDetails1.liked = false;
      postDetails1.likes -= 1;

      return {
        ...state,
        postDetails: postDetails1
      };
    case "CLEAR_POST_DATA":
      return initialState;
    default:
      return state;
  }
};

export default postsReducer;

postsActions.js

import Axios from "axios";
import moment from "moment";
import store from "../store";
export const createPost = postData => {
  return (dispatch, getState) => {
    dispatch({ type: "CREATING_POST" });

    Axios.post("/api/post/new", {
      imageUrl: postData.imageUrl,
      caption: postData.caption
    })
      .then(res => {
        dispatch({ type: "CREATED_POST" });

        dispatch({ type: "ADD_POST", payload: res.data.post });
      })
      .catch(err => {
        console.log(err);
      });
  };
};

export const fetchFeed = () => {
  return (dispatch, getState) => {
    Axios.get("/api/user/feed")
      .then(res => {
        var feed = res.data.feed;
        const state = store.getState();
        const likedPosts = state.user.userData.likedPosts;

        for (var i = 0; i < feed.length; i++) {
          for (var j = 0; j < feed.length - i - 1; j++) {
            if (moment(feed[j + 1].createdAt).isAfter(feed[j].createdAt)) {
              var temp = feed[j];
              feed[j] = feed[j + 1];
              feed[j + 1] = temp;
            }
          }
        }

        for (var i = 0; i < feed.length; i++) {
          if (likedPosts.indexOf(feed[i]._id) > -1) {
            feed[i]["liked"] = true;
          } else {
            feed[i]["liked"] = false;
          }
        }

        console.log(feed);
        dispatch({ type: "FETCH_FEED", payload: feed });
      })
      .catch(err => {
        console.log(err);
      });
  };
};

export const likePost = postId => {
  return (dispatch, getState) => {
    Axios.put("/api/post/like", { postId: postId })
      .then(res => {
        const feed = store.getState().posts.feed;

        feed.forEach(post => {
          if (post._id === postId) {
            post.liked = true;
          }
        });

        dispatch({ type: "UPDATE_FEED", payload: feed });
        dispatch({ type: "LIKED_POST", payload: res.data.postId });
      })
      .catch(err => {
        console.log(err);
      });
  };
};

export const unlikePost = postId => {
  return (dispatch, getState) => {
    Axios.put("/api/post/unlike", { postId: postId })
      .then(res => {
        const feed = store.getState().posts.feed;

        feed.forEach(post => {
          if (post._id === postId) {
            post.liked = false;
          }
        });

        dispatch({ type: "UPDATE_FEED", payload: feed });
        dispatch({ type: "UNLIKED_POST", payload: res.data.postId });
      })
      .catch(err => {
        console.log(err);
      });
  };
};

export const getPostData = postId => {
  return (dispatch, getState) => {
    Axios.get(`/api/post/${postId}`)
      .then(res => {
        const likedPosts = store.getState().user.userData.likedPosts;

        if (likedPosts.indexOf(postId) > -1) {
          res.data.post["liked"] = true;
        } else {
          res.data.post["liked"] = false;
        }

        dispatch({ type: "GET_POST_DATA", payload: res.data.post });
      })
      .catch(err => {
        console.log(err);
      });
  };
};

export const resetFeedUpdated = () => {
  return (dispatch, getState) => {
    dispatch({ type: "RESET_FEED_UPDATED" });
  };
};

export const resetCreatedPost = () => {
  return (dispatch, getState) => {
    dispatch({ type: "RESET_CREATED_POST" });
  };
};

3 个答案:

答案 0 :(得分:2)

您的LIKED_POSTUNLIKED_POST的化简用例不是纯正的-它们正在使状态中现有的postDetails对象发生变异,并将其放回到state中,所以{{1 }}在connect中对postDetails的上一个和下一个道具进行浅等式比较时,正在优化而不是重新渲染。确保为componentShouldUpdate创建一个全新的值,例如:

postDetails

答案 1 :(得分:0)

您应该检查比较if (prevProps.postDetails !== this.props.postDetails)是否命中。因为使用like函数,您仅更改同一对象的属性,所以比较将失败,因为它仍然是postDetails的相同对象引用。尝试在减速器中返回一个新对象:

case "LIKED_POST":
      const { postDetails } = state;

      postDetails.liked = true;
      postDetails.likes += 1;
      return {
        ...state,
        postDetails: {
           ...postDetails
        },
      }

如果您不更改组件内部的任何对象,但在Redux存储中,为什么不直接使用component属性呢?您可以删除状态对象和componentDidUpdate。您也可以将其重构为功能组件。

  render() {
    const { postDetails: postData } = this.props;
    ...
  }

答案 2 :(得分:0)

使用Redux时,请不要忘记三个原则

  • 真理的唯一来源
  • 状态仅准备就绪
  • Reducer必须是纯函数:Reducer采取先前的状态和某些操作并对其进行修改并返回新状态。我们绝不应该改变状态。我们应该创建新对象并返回它们。

您已简化化简函数中的现有状态。这不会触发componentdidupdate,因为connect方法(它检查mapStateToProps)认为没有任何更改(它检查引用,并且因为引用没有更改,所以未调用Component)。

您可以使用Object.assign或使用散布运算符,这有助于使减速器返回新对象。

更改喜欢的和未链接的帖子精简器功能,以返回一个新对象,而不是对现有对象进行变异。

@azundo添加了应该如何实现您的代码。