我正在尝试使用reactjs来更新状态,一旦状态更新,就会触发一个ajax调用,请求一个新页面。就在触发ajax调用之前,设置了一个偏移量变量:var offset = this.state.npp * this.state.page;
然而,我发现在触发clickNextPage()之后,this.state.page的值并没有更新。
我根本不明白这里发生了什么,这似乎是一个竞争条件,因为我用{this.state.page}观察了我的render()函数的状态变化。
如何确保更新我的this.state.page,然后触发findByName()?
clickNextPage: function(event){
console.log("clicked happend")
page = this.state.page;
console.log(page)
page += 1
console.log(page)
this.setState({page: page});
console.log(this.state.page)
this.findByName()
},
JS控制台:
clicked happend
0
1
0
发布于 2015-09-12 06:19:55
this.state
不会立即更新,因此setState
是异步的。对您的困境的简短回答是使用回调(setState
的第二个参数),该回调在内部状态更新后调用。例如
this.setState({page: page}, function stateUpdateComplete() {
console.log(this.state.page)
this.findByName();
}.bind(this));
更长的答案是,在您调用setState
之后,将调用三个函数(有关每个https://facebook.github.io/react/docs/component-specs.html的更多详细信息,请参阅此处):
shouldComponentUpdate
这使您可以检查以前的状态和新的状态,以确定组件是否应该自我更新。如果返回false,则以下函数将不会被执行(尽管在component)componentWillUpdate
中仍会更新,但这使您有机会在内部设置新状态之前运行任何代码,并且呈现在组件“functions.componentDidUpdate
”和“”之间发生这种情况)这使您有机会在设置了新状态并且组件已重新呈现其自身之后运行任何代码发布于 2015-09-12 06:08:32
当调用this.setState
时,新状态不是直接设置的,React会将其置于挂起状态,通过调用this.state
可以返回旧状态。
这是因为React可能会批量处理您的状态更新,因此无法保证this.setState
是同步的。
您要做的是在componentDidUpdate
、componentWillUpdate
中调用this.findByName()
,或者根据您的用例通过回调将其作为第二个参数提供给this.setState
。请注意,直到您的调用传递并且组件重新呈现自身之后,才会触发对this.setState
的回调。
此外,在您的示例中,您可以传递一个函数do this.setState
来提高可读性,而不是进行变量跳跃。
this.setState(function (prevState, currentProps) {
return {page: prevState.page + 1}
}, this.findByName);
发布于 2019-06-13 04:00:14
使用无名函数,可以用更短的格式编写此代码。
myReactClassFunction = (param) => {
this.setState({
key: value,
},
() => this.myClassFunction());
}
https://stackoverflow.com/questions/32530134
复制相似问题