Javascript 如何使用nextProps值在React componentWillReceiveProps方法中编写整洁的代码
我想优化上面的代码Javascript 如何使用nextProps值在React componentWillReceiveProps方法中编写整洁的代码,javascript,reactjs,react-redux,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. } 通过这种方式,您可以像妻子一样优化和使用变量,而无需任何更改值。如果next
componentWillReceiveProps(nextProps) {
this.setState({executor : nextProps.executor, wife : nextProps.wife});
// Some filtering and functional Operation on nextProps value of wife and executor.
}
通过这种方式,您可以像妻子一样优化和使用变量,而无需任何更改值。如果
nextProps
只有两个对象executor
和妻子
,则可以在一行中设置它
componentWillReceiveProps(nextProps) {
const {executor, wife} = nextProps;
this.setState({executor, wife});
// Some filtering and functional Operation on nextProps value of wife and executor.
}
或者按照@Harsh的方式定义一个常数
componentWillReceiveProps(nextProps) {
this.setState(nextProps,()=>{
// Your callback after it sets the state
// Some filtering and functional Operation on nextProps value of wife and executor.
});
}
使用ES6销毁,还添加了安全的默认对象值
const {executor, wife} = nextProps;
this.setState({executor, wife});
使用新的getDerivedStateFromProps
如果您正在使用React 16,请使用新的getDerivedStateFromProps方法执行相同的操作,因为componentWill***
方法现在已被弃用。另外,请注意,它是一种静态方法。阅读更多关于这种新方法的信息
componentWillReceiveProps({executor, wife} = {}) {
this.setState({executor, wife});
}
static getDerivedStateFromProps(props, state) {
return {
props.executor,
props.wife
}
}