以下是我的 React 组件中的代码摘要:
getInitialState: function(){
return{link:""}
},
onClick1: function(){
this.setState({link:"Link1"});
this.otherFunction();
},
onClick2: function(){
this.setState({link:"Link2"});
this.otherFunction();
},
otherFunction:function(){
//API call to this.state.link
},
render: function(){
return <div>
<button1 onClick={this.onClick1}>Link1</button>
<button2 onClick={this.onClick2}>Link2</button>
//...some code to display the results of API call
</div>
}
我遇到的问题是,第一次单击该按钮时, otherFunction 将运行,但它不会具有 myState 的更新值。如果我第二次单击,则它可以正常工作。
来自docs:
setState()
不会立即变异this.state
但会创建一个挂起的状态转换。访问this.state
调用此方法后可能会返回现有值。
不保证调用的同步操作setState
并且可以对调用进行批处理以提高性能。
如果您希望函数在状态转换完成后执行,请将其作为回调传递:
onClick1: function() {
this.setState({link:"Link1"}, this.otherFunction);
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)