【问题标题】:In React 16.7, after setState call, getDerivedStateFromProps returning null is also updating state在 React 16.7 中,在 setState 调用之后,返回 null 的 getDerivedStateFromProps 也正在更新状态
【发布时间】:2019-07-18 02:55:38
【问题描述】:

组件被渲染后,我调用 updateResults 方法,该方法调用 setState,然后调用 getDerivedState 并返回 null,仍然状态正在更新并调用 render 和 componentDidUpdate。

根据docs,它不应该发生。谁能解释一下为什么会这样?

class Results extends React.Component{
  constructor(props){
    super(props);
    this.state = {"query":props.data.web_query,"other_fields":props.other_fields};
  }  

  static getDerivedStateFromProps(props, state) {

    if (state.query != props.data.web_query) {  
      console.log("Returning new state as expected");
      state.query = props.data.web_query;
      return state;
    }
    console.log("Returning null, shouldn't change state, but changing");

    return null;
 }

  componentDidUpdate() {
    console.log("Componenent Did update");
  }

  updateResults(){
       let results = someAjaxCall(); 
       this.setState({"query":results.data.webquery,
                      "other_fields":results.other_fields});

  }

  render(){
      <SomeComponent updateCall={this.updateResults}/>
   }
}

另外,请解释一下 setState 与 getDerivedStateFromProps 和 shouldComponentUpdate 的关系?

【问题讨论】:

  • 请发表一分钟。可重现的回购,所以我们可以看看
  • 状态变为什么?
  • 无论状态如何变化(即返回更新后的状态对象或 null),都会调用您的渲染方法。
  • 但如果它返回 null,则不应更改状态。它也在改变状态。
  • 那个状态会变成什么?空?

标签: javascript reactjs


【解决方案1】:

我想你没有理解 getDerivedStateFromProps() 的目的

此方法用于在道具发生变化时更新状态。

即使在 setState 之后调用该方法,如果 getDerivedStateFromProps 返回 null 状态也会使用 setState 内部的数据进行更新,但 getDerivedStateFromProps 可以覆盖某些属性。

【讨论】:

  • 好的。这听起来合乎逻辑。
猜你喜欢
  • 1970-01-01
  • 2018-12-03
  • 2020-10-25
  • 2019-07-09
  • 2019-01-28
  • 1970-01-01
  • 2017-09-16
  • 2019-12-21
  • 2017-07-23
相关资源
最近更新 更多