在使用有状态的 React 组件时,我经常遇到这种情况。
我需要对 props 做一些操作 - 要么做一些我现在想在 render()
中进行的处理,要么根据 props 中的值设置状态。
因为我想在最初安装组件时以及更新 props 时执行此操作,所以我最终得到了这样的样板代码:
constructor(){
super(props)
const modifiedProps = doSomethingWithProps(props)
...
this.state = {initialState}
}
componentWillReceiveProps(nextProps) {
const modifiedProps = doSomethingWithProps(nextProps)
...
this.setState({newState})
}
doSomethingWithProps(props){
...
}
有没有更好的方法来做到这一点?
最佳答案
根据问题的评论回答,我觉得很有帮助 --
如果有一堆工作需要根据props
来完成,componentWillMount
允许你使用this.setState()
您的辅助函数并最大限度地减少在 constructor
中完成的工作。这可以清理一堆重复的代码。
constructor(){
super(props)
this.state = {initialState}
}
componentWillMount() {
this.doSomethingWithProps(this.props);
}
componentWillReceiveProps(nextProps) {
this.doSomethingWithProps(nextProps)
}
doSomethingWithProps(props){
...
this.setState({newState})
}
关于javascript - React 组件构造函数和 componentWillReceiveProps 中的常用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436526/