【发布时间】: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