本篇文章给大家带来的内容是关于react下setstate机制的简单介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
api解析: setstate(updater, [callback])
updater: 更新数据 function/object
callback: 更新成功后的回调 function
// updater - functionthis.setstate((prevstate, props) => { return {counter: prevstate.counter + props.step};});// update - objectthis.setstate({quantity: 2})
setstate的特点:
1.异步:react通常会集齐一批需要更新的组件,然后一次性更新来保证渲染的性能
2.浅合并 objecr.assign()
带来的问题与解决
在使用setstate改变状态之后,立刻通过this.state去拿最新的状态
解决: componentdidupdate或者setstate的回调函数里获取
// setstate回调函数changetitle: function (event) { this.setstate({ title: event.target.value }, () => this.apicallfunction());},apicallfunction: function () { // call api with the updated value}
有一个需求,需要在在onclick里累加两次,使用对象的方法更新,则只会加一次
解决: 使用updater function
onclick = () => { this.setstate({ index: this.state.index + 1 }); this.setstate({ index: this.state.index + 1 });}// 最后解析为,后面的数据会覆盖前面的更改,所以最终只加了一次.object.assign( previousstate, {index: state.index+ 1}, {index: state.index+ 1},)//正确写法onclick = () => { this.setstate((prevstate, props) => { return {quantity: prevstate.quantity + 1}; }); this.setstate((prevstate, props) => { return {quantity: prevstate.quantity + 1}; });}
建议:
1.不要在render()函数里面写setstate(),除非你自己定制了shouldcomponentupdate方法,要不然会引起无限循环
2.不能给state直接赋值,不会引发render eg: this.state.num = 2
3.对数组和对象等引用对象操作时,使用返回新对象的方法
array: 不要使用push、pop、shift、unshift、splice可使用concat、slice、filter、扩展语法
object: object.assgin/扩展语法
setstate更新机制
如图: pending queue 和 update queue
以上就是react下setstate机制的简单介绍的详细内容。