我正在重构已弃用的生命周期方法componentWillRecieveProps()
及其新的继任者static getDerivatedPropsFromState()
我面对这个重构的问题是componentWillRecieveProps()
使用了一个类函数:
componentWillRecieveProps(nextProps) {
if(this.props.theme !== nextProps.theme) {
this.changeTheme()
}
}
所以当我尝试在新的生命周期方法中访问这个函数时:
static getDerivatedPropsFromState(nextProps, prevState) {
if(prevState.theme !== nextProps.theme) {
this.changeTheme();
return { prevState: nextProps.theme };
}
return null;
}
错误跳转this.changeTheme() is undefined
。
我应该如何在static getDerivatedPropsFromState()
?
对于为什么会发生这种情况的任何帮助和解释都将非常感激。
答案 0 :(得分:1)
add_index :contacts, :title, using: :gist, opclass: {title: :gist_trgm_ops}
仅用于更新状态。如果您计划进行更新,则应使用getDerivatedPropsFromState
代替componentDidUpdate
。
在博客中提到:
此组件的建议升级路径是将数据更新移至
componentWillReceiveProps
。您还可以使用新的getDerivedStateFromProps生命周期在呈现新道具之前清除陈旧数据。
所以而不是
componentDidUpdate
另一种方法是做到这一点
componentWillRecieveProps(nextProps){
if(this.props.theme !== nextProps.theme){
this.changeTheme()
}
}