代码之家  ›  专栏  ›  技术社区  ›  CodeZombie

比较Reactjs中的prevProps和nextProps的最佳方法是什么?

  •  0
  • CodeZombie  · 技术社区  · 8 年前

    子组件正在从其父组件接收许多更新的道具。如果道具中有任何更新,我想更新子组件。当前,我正在使用生命周期方法进行更新 componentWillReceiveProps 一切如期而至。

    componentWillReceiveProps(nextProps){
        if(this.props.scale_length !== nextProps.scale_length){
          const {scale_height,scale_breadth} = this.props
          this.setState({
            torsoScale: new 
                THREE.Vector3(nextProps.scale_length,scale_height,scale_breadth)
          });
        }
    if(this.props.scale_breadth !== nextProps.scale_breadth){
          const {scale_height,scale_length} = this.props
          this.setState({
            torsoScale: new 
                THREE.Vector3(scale_length,scale_height,nextProps.scale_breadth)
          });
        }
    
    ...
    }
    

    但是,我以后会得到8个以上的道具。我该怎么做呢。谢谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   We Are All Monica    8 年前

    如果道具中有任何更新,我想更新子组件。

    默认情况下,React就是这样做的!您应该使用它的常规组件更新,而不是试图与之抗争,并决定是否自己更新。

    getDerivedStateFromProps 为此,可能还有更好的方法,比如直接在 render 方法。

    以下是一篇更详细的文章: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html