反应js getDerivedStateFromProps不断调用

时间:2020-09-11 12:59:08

标签: reactjs react-native

for key, value in dictionary.items():
    dictionary[key] = ' '.join(value)

我正在将我的React应用程序从16.3迁移到最新版本。我有一个问题,其中getDerivedStateFromProps()连续调用,因为状态在toggle()中正在更新。道具更新后,我需要调用toggle()

帮我解决问题。

2 个答案:

答案 0 :(得分:1)

getDerivedStateFromProps在每个渲染器上运行。它也是静态方法,因此不应称为setState(或其他非静态函数)。在文档中,React指出,在大多数情况下,您不需要这种方法即可根据道具更改here来实现状态更改。

因此,第一个选项是不要调用setState,它会触发重新渲染,并且重新渲染将运行getDerivedStateFromProps。本质上是无限的重新渲染循环。

static getDerivedStateFromProps(props, state) {
    if (props.myStateVar !== state.myStateVar) {
        return {
           myStateVar: props.myStateVar,
           otherStateVar: [] // from toggle
        }
    }

    // Should not be called everytime this method runs. Only when props change
    // toggle() //Need to call the function each time when we get the props update
    return null;
}

您的另一个选择是备忘录,在我提供的链接中对此进行了详尽的介绍。

答案 1 :(得分:1)

您为什么不为此使用componentDidUpdate?在我看来,您可以通过以下方式获得结果:

/**
 * @param {Props} prevProps props of the component
 **/
componentDidUpdate(prevProps) {
  if (prevProps.myStateVar !== this.props.myStateVar) {
    this.setState({ myStateVar: this.props.myStateVar });
    toggle();
  }
}
相关问题