仅当我刷新页面时,componentWillReceiveProps才会更新状态

时间:2019-02-09 15:47:59

标签: reactjs firebase react-redux

大家好,你能帮我吗?

我正在使用react + firebase + redux

该类的最后几行如下所示(编辑帖子页):

const mapStateToProps = (state, ownProps) => {
  const id = ownProps.match.params.id;
  const posts = state.firestore.data.posts;
  const post = posts ? posts[id] : null;
  return {
    post: post,
    auth: state.firebase.auth
  };
};

const mapDispatshToProps = (dispatch, ownProps) => {
  return {
    editPost: (id, post) => dispatch(editPost(id, post, ownProps.history))
  };
};

export default compose(
  connect(
    mapStateToProps,
    mapDispatshToProps
  ),
  firestoreConnect([{ collection: "posts" }])
)(CreatePost);

之后,我使用componentDidMount来获得这样的帖子:

componentDidMount() {
    const post = this.props.post;
    console.log(post);

    this.setState({
      title: post ? post.title : "",
      content: post ? post.content : ""
    });
  }

我还使用了componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    const { post } = nextProps;
    console.log(post);
    this.setState({
      title: post.title,
      content: post.content
    });
  }

我的ipnut看起来像这样:

<input type="text" id="title" value={this.state.title} onChange={this.handleChange} />

控制台始终显示null

我没有成功更新状态(查看更新的唯一方法是刷新页面)

你能帮我吗

谢谢

3 个答案:

答案 0 :(得分:0)

我认为您可能会忘记在代码中调用调度功能。 例如,像这样:     this.props.editPost(id,post); //这将更新您的redux存储的数据。 然后您可以从Redux存储中获取更新的数据。

答案 1 :(得分:0)

componentWillReceiveProps已过时,请使用componentDidUpdate

componentDidUpdate(prevProps) {
  if(prevProps.post !== this.props.post) {
    const { post } = this.props;
    console.log(post);
    this.setState({
      title: post.title,
      content: post.content
    });
  }
}

答案 2 :(得分:0)

问题已解决,谢谢大家:

解决方案: 而不是使用这个:

componentDidMount() {
    const post = this.props.post;
    console.log(post);

    this.setState({
    title: post ? post.title : "",
    content: post ? post.content : ""
  });
}

我这样使用static getDerivedStateFromProps

  static getDerivedStateFromProps(nextProps, state) {
    const { post } = nextProps;
    return {
      title: post ? post.title : "",
      content: post ? post.content : ""
    };
  }

谢谢Piotr Szlagura