【问题标题】:react js getDerivedStateFromProps is calling continuouslyreact js getDerivedStateFromProps 不断调用
【发布时间】:2020-12-30 00:11:16
【问题描述】:
constructor(props) {
    super(props);
    this.state = {
        myStateVar: []
    }
}

static getDerivedStateFromProps(props, state) {
    if (props.myStateVar !== state.myStateVar) {
        return {
           myStateVar: props.myStateVar
        }
    }

    toggle() //Need to call the function each time when we get the props update
    return null;
}

toggle() {
    this.setState({
        otherStateVar: []
    })
}

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

帮我解决问题。

【问题讨论】:

  • 您可以为此使用 componentDidUpdate。
  • componentDidUpdate 不会正确获取道具更改/更新?
  • componentDidUpdate 将使用 prevProps 作为参数调用。你可以在那里检查情况。我添加了一个反映它的答案

标签: reactjs react-native


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    getDerivedStateFromProps 在每次渲染上运行。它也是一个静态方法,因此不应将其称为 setState(或其他非静态函数)。在文档中,React 指出大多数时候你不需要这个方法来实现基于 prop 变化的状态变化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;
    }
    

    您的另一个选择是记忆,我提供的那个链接中已经详细介绍了它。

    【讨论】:

    • 感谢您的回复。我在 toggle() 中有一些计算和功能,我需要根据计算更新那里的状态
    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2020-09-11
    • 2019-02-21
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多