【问题标题】:How can getDerivedStateFromProps method can access state if the state is initialized from within the constructor(props)?如果从构造函数(props)中初始化状态,getDerivedStateFromProps 方法如何访问状态?
【发布时间】:2021-01-05 08:21:25
【问题描述】:

大家好,我是 ES6React 的新手,我被困在 react 的组件生命周期创建中。我的问题是在我的构造函数中我已经初始化了状态..

constructor(props) {
    super(props);
    this.state = {
    ....something
}

现在在 react 的组件生命周期创建中,我们有 getDerivedStateFromProps 这是一个静态函数,它接受两个参数 props 和以前的状态,您可能会返回当前状态左右,具体取决于您是否从 props 更改状态

static getDerivedStateFromProps (props, state) {
    ... do something
    return state;
}

这个静态函数如何能够访问或拥有在constructor() 中初始化的属性,该属性将在运行时或创建对象时运行?静态函数不是在类加载时在运行时之前运行,那么它如何访问状态对象?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    并且您可能会返回当前状态左右,具体取决于您是否从道具更改状态

    不,您返回一个状态 update(要更改的内容,未完成状态 [尽管完成状态也可以]),或者不返回任何内容/返回 undefined 以表示没有更新。

    这个静态函数如何能够访问或拥有在 constructor() 中初始化的属性,该属性将在运行时或创建对象时运行?

    它没有。正如你所说,React 调用函数传入状态作为参数。想一想调用它的 React 代码模糊地看起来像这样:

    
    const stateUpdate = YourComponentClass.getDerivedStateFromProps(
        componentInstance.state,
        componentInstance.props
    );
    // (Then it uses `stateUpdate` to set the state immediately)
    

    我确定不是真的,但从概念上讲,它就是这样做的。

    getDerivedStateFromProps 是静态的,因此人们不会在其中做改变实例的事情,因为他们无权访问实例。

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2019-08-06
      • 2017-08-17
      • 2020-04-04
      • 2019-12-03
      • 2015-05-10
      • 2019-05-08
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多