JZ.*_*JZ. 12 state race-condition reactjs
我正在尝试使用reactjs来更新状态,一旦更新,就会激活一个请求新页面的ajax调用.就在ajax调用触发之前设置了一个偏移量变量:var offset = this.state.npp * this.state.page;但是我发现clickNextPage()被触发后,this.state.page的值不会更新.
我从根本上不明白这里发生了什么,这似乎是一个竞争条件,因为我用{this.state.page}观察我的render()函数的状态变化.
如何确保更新my.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()
},
Run Code Online (Sandbox Code Playgroud)
JS控制台:
clicked happend
0
1
0
Run Code Online (Sandbox Code Playgroud)
Ed *_*lot 13
setState是异步的,this.state不会立即更新.对你的窘境的简短回答是使用在setState更新内部状态后调用的回调(第二个参数).例如
this.setState({page: page}, function stateUpdateComplete() {
console.log(this.state.page)
this.findByName();
}.bind(this));
Run Code Online (Sandbox Code Playgroud)
更长的答案是,在您调用之后,会调用setState三个函数(有关每个https://facebook.github.io/react/docs/component-specs.html的更多详细信息,请参阅此处):
shouldComponentUpdate这允许您检查先前和新状态以确定组件是否应更新自身.如果返回false,则不执行以下函数(尽管this.state仍将在组件中更新)componentWillUpdate 这使您有机会在内部设置新状态并进行渲染之前运行任何代码render 这发生在组件"will"和"did"函数之间.componentDidUpdate 这使您有机会在设置新状态并且组件重新自我渲染后运行任何代码| 归档时间: |
|
| 查看次数: |
4288 次 |
| 最近记录: |