如何使用nextProps值在React componentWillReceiveProps方法中编写简洁的代码

时间:2018-07-17 11:08:19

标签: javascript reactjs react-redux

componentWillReceiveProps(nextProps) {
  this.setState({executor : nextProps.executor, wife : nextProps.wife});

  // Some filtering and functional Operation on nextProps value of wife and executor.
}

我想优化上面的代码。

4 个答案:

答案 0 :(得分:1)

componentWillReceiveProps(nextProps) {
  const {executor, wife} = nextProps;
  this.setState({executor, wife});

  // Some filtering and functional Operation on nextProps value of wife and executor.
}

通过这种方式,您可以像妻子一样优化和使用变量,而无需更改任何值。

答案 1 :(得分:1)

如果nextProps只有两个对象executorwife,则可以将其设置为一行

componentWillReceiveProps(nextProps) {
  this.setState(nextProps,()=>{
    // Your callback after it sets the state
    // Some filtering and functional Operation on nextProps value of wife and executor.
  });
}

或者用@Harsh定义常量的方式回答

const {executor, wife} = nextProps;
this.setState({executor, wife});

答案 2 :(得分:1)

  

使用新的 getDerivedStateFromProps

如果您正在使用React 16,因为现在不推荐使用componentWill***方法,请使用新的 getDerivedStateFromProps 方法执行相同的操作。另外,请注意,这是一种静态方法。了解有关此新方法here的更多信息。

static getDerivedStateFromProps(props, state) {
    return {
      props.executor,
      props.wife
    }
}

答案 3 :(得分:0)

使用ES6销毁,还添加了默认对象值以确保安全。

componentWillReceiveProps({executor, wife} = {}) {
   this.setState({executor, wife});
}