Javascript 在React 16.7中,在setState调用之后,返回null的getDerivedStateFromProps也在更新状态
在呈现组件之后,我调用updateResults方法,该方法调用setState,之后调用getDerivedState并返回null,静止状态得到更新,并调用render和componentDidUpdate 根据法律,这不应该发生。有人能解释一下为什么会这样吗Javascript 在React 16.7中,在setState调用之后,返回null的getDerivedStateFromProps也在更新状态,javascript,reactjs,Javascript,Reactjs,在呈现组件之后,我调用updateResults方法,该方法调用setState,之后调用getDerivedState并返回null,静止状态得到更新,并调用render和componentDidUpdate 根据法律,这不应该发生。有人能解释一下为什么会这样吗 class Results extends React.Component{ constructor(props){ super(props); this.state = {"query":props.data.w
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}/>
}
}
类结果扩展了React.Component{
建造师(道具){
超级(道具);
this.state={“query”:props.data.web_query,“other_fields”:props.other_fields};
}
静态getDerivedStateFromProps(props,状态){
如果(state.query!=props.data.web_query){
log(“按预期返回新状态”);
state.query=props.data.web\u查询;
返回状态;
}
log(“返回null,不应更改状态,但应更改”);
返回null;
}
componentDidUpdate(){
日志(“组件未更新”);
}
updateResults(){
让结果=someAjaxCall();
this.setState({“query”:results.data.webquery,
“其他_字段”:results.other_字段});
}
render(){
}
}
另外,请解释setState与getDerivedStateFromProps的关系&是否应该更新组件?我想您不理解getDerivedStateFromProps()的用途 此方法用于在道具更改时更新状态
即使在setState之后调用该方法,如果getDerivedStateFromProps返回null,则状态将使用setState中的数据进行更新,但getDerivedStateFromProps可以覆盖某些属性 请发布一个最小可复制的repo,以便我们可以查看状态更改为什么?无论状态如何更改(即返回更新的状态对象或null),都将调用您的呈现方法。但如果它返回null,则不应更改状态。它也在改变状态。那个状态会变成什么?空?好的。这听起来合乎逻辑。