【问题标题】:Lifecycle method static getDerivedStateFromProps doesn't work as expected生命周期方法静态 getDerivedStateFromProps 无法按预期工作
【发布时间】:2020-05-02 15:19:03
【问题描述】:

我有一个组件,我为它设置了初始状态。在我的情况下,当我更改复选框状态时,父组件应该发送带有标志“true”或“false”的新属性,如果我在我的渲染方法中 console.log 它会这样做。但是,如果我使用生命周期方法静态 getDerivedStateFromProps - 它只显示来自先前状态和新道具的更新值(如“true”、“true”而不是先前的“false”和新的“true”)。问题是:想不通,这里的陷阱在哪里?如果我在我的渲染方法中 console.log 它会发送新的道具,但 getDerivedStateFromProps 在 prevState 和 newProps 中显示相同的值。

class MyComponent extends React.PureComponent {
 state = {
   stateValue: this.props.myValue
 }

 handleChange = () => {
   // Custom parent method which change checkbox state and send new props to MyComponent
   this.props.onChange(...)
 }

 static getDerivedStateFromProps(nextProps, prevState) {
        const { myNextProperty } = nextProps
        const { myPrevStateProperpty } = prevState
        debugger
        if (myNextProperty !== myPrevStateProperpty) {
            return {
                stateValue: nextProps,
            }
        }
        return null
    }

    render() {
       const { stateValue } = this.state

       return (
           <MyViewComponent onChange={this.handleChange} value={stateValue} />
       )
    }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    尝试componentDidUpdate 并记住this.props 总是新鲜的this.props == nextProps,避免在状态下复制道具,当你必须这样做时,你应该用defaultProp 指定它,等等......

    class Button extends React.PureComponent {
      render() {
        const textColor = slowlyCalculateTextColor(this.props.color);
        return (
          <button className={
            'Button-' + this.props.color +
            ' Button-text-' + textColor // ✅ Always fresh
          }>
            {this.props.children}
          </button>
        );
      }
    }
    

    或者更好的 Hooks 解决方案:

    function Button({ color, children }) {
      const textColor = useMemo(
        () => slowlyCalculateTextColor(color),
        [color] // ✅ Don’t recalculate until `color` changes
      );
      return (
        <button className={'Button-' + color + ' Button-text-' + textColor}>
          {children}
        </button>
      );
    }
    

    【讨论】:

      【解决方案2】:

      我不确定为什么它对您不起作用,可能是因为字段 myNextPropertymyPrevStateProperty 或者因为您没有在此处提供的 this.props.onChange 函数。但是我实现了您的代码并且它可以工作,您可以在控制台中看到prevStatenextProps 的值不同:

      https://codesandbox.io/embed/practical-monad-93ztc?fontsize=14&hidenavigation=1&theme=dark

      【讨论】:

        【解决方案3】:
        state = {
          stateValue: this.props.myValue
        }
        

        您将 myValue 存储在 stateValue 中,但比较其他内容:

        static getDerivedStateFromProps(nextProps, prevState) {
         //   const { myNextProperty } = nextProps
         //   const { myPrevStateProperpty } = prevState
            debugger
            if (myNextProperty !== myPrevStateProperpty) {
                return {
                    stateValue: nextProps,
                }
            }
            return null
        }
        

        可能你需要类似的东西:

        static getDerivedStateFromProps(nextProps, prevState) {
         //   const { myNextProperty } = nextProps
         //   const { myPrevStateProperpty } = prevState
            debugger
            if (nextProps.myValue !== prevState.stateValue) {
                return {
                    stateValue: nextProps.myValue,
                }
            }
            return null
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-12
          • 2013-09-21
          • 1970-01-01
          • 2017-04-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多