访问static getDerivatedPropsFromState中的类函数

时间:2018-04-03 22:07:04

标签: javascript reactjs

我正在重构已弃用的生命周期方法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()

中引用此功能

对于为什么会发生这种情况的任何帮助和解释都将非常感激。

1 个答案:

答案 0 :(得分:1)

add_index :contacts, :title, using: :gist, opclass: {title: :gist_trgm_ops} 仅用于更新状态。如果您计划进行更新,则应使用getDerivatedPropsFromState代替componentDidUpdate

请参阅https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change

在博客中提到:

  

此组件的建议升级路径是将数据更新移至componentWillReceiveProps。您还可以使用新的getDerivedStateFromProps生命周期在呈现新道具之前清除陈旧数据。

所以而不是

componentDidUpdate

另一种方法是做到这一点

componentWillRecieveProps(nextProps){
  if(this.props.theme !== nextProps.theme){
    this.changeTheme()
  }
}