【问题标题】:How to make use of React setState method using getDerivedStateFromProps?如何使用 getDerivedStateFromProps 使用 React setState 方法?
【发布时间】:2021-04-11 04:20:01
【问题描述】:

在我的代码中,我使用了componentWillReceiveProps,我知道它已被弃用,但我的代码使用该方法似乎工作正常。这就是我所拥有的:

componentWillReceiveProps(nextProps) {
    if(nextProps.tableData !== undefined) {
      const data = nextProps.tableData.datapaths.map(item => { return item.row });
      this.setState({ data });
    }
  }

谁能告诉我如何将相同的逻辑应用于方法getDerivedStateFromProps,因为当我尝试在此方法中使用setState 方法时它不喜欢并抱怨:

static getDerivedStateFromProps(props, state) {
    if (props.tableData !== undefined) {
      const data = props.tableData.datapaths.map(item => { return item.row });
      state.data = data;
      this.setState({ data });
    }
  }

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

您不应该在 getDerivedStateFromProps 中使用 setState ,只需返回新状态即可:

static getDerivedStateFromProps(props, state) {
  if (props.tableData !== undefined) {
    const data = props.tableData.datapaths.map(item => { return item.row });

    // this will update the state
    return { data };
  }
}

【讨论】:

  • 我已经尝试过了,但我仍然没有看到在桌子上进行排序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2016-12-18
  • 1970-01-01
  • 2019-06-16
  • 2018-09-12
  • 1970-01-01
相关资源
最近更新 更多