首页 > 解决方案 > 在 React 的 getDerivedStateFromProps 中调用异步函数

问题描述

当状态更新时,我需要更新表。因此,我尝试在 getDerivedStateFromProps 中调用函数更新,但似乎我无法在 getDerivedStateFromProps 中使用“this”。有没有办法做到这一点?预先感谢。

static getDerivedStateFromProps(props, state) {
    if(props.newValue != state.newValue) {
      this.updateTable();
      return {
        newValue : props.newValue 
      }
    }
    return null;
  }

标签: reactjs

解决方案


updateTable是一个sideEffect不需要存在的函数getDerivedStateFromProps

getDerivedStateFromProps有意编写为静态函数,因此您无法从中调用类实例函数

为了处理 sideEffect 你必须在 componentDidUpdate 函数中执行它们

 componentDidUpdate(prevProps, prevState) {
    if(this.props.newValue != prevProps.newValue) {
      this.updateTable();
    }
  }

推荐阅读