0

子组件正在从其父组件接收许多更新的道具。如果道具中有任何更新,我想更新子组件。目前,我正在使用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 个以上的道具。我将如何继续。谢谢。

4

1 回答 1

1

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

这就是 React 默认做的!您应该使用它的正常组件更新,而不是试图对抗它并决定是否自己更新东西。

你可以使用getDerivedStateFromProps它,但可能还有更好的方法,比如直接在render方法中计算向量。

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

于 2018-08-21T06:44:50.033 回答