代码之家  ›  专栏  ›  技术社区  ›  ABS zarzis

只有刷新页面时,ComponentWillReceiveProps才会更新状态

  •  0
  • ABS zarzis  · 技术社区  · 6 年前

    大家好,你们能帮我一下吗?

    我正在使用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 回复  |  直到 6 年前
        1
  •  0
  •   J.Odrin    6 年前

    我认为您可能忘记了在代码中调用分派函数。 例如,如下所示: this.props.editpost(id,post);//这将更新Redux存储区的数据。 然后您可以从Redux存储中获取更新的数据。

        2
  •  0
  •   Mohamed Ramrami    6 年前

    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
        });
      }
    }
    
        3
  •  0
  •   ABS zarzis    6 年前

    问题解决了,谢谢大家:

    解决方案: 使用本产品的先例:

    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