对react setState 的理解
setState是异步的,对于这个我们随便测试一些就知道的,关于为什么是异步的可以参考博客的一些见解。
我们翻开react源码(version:16.3.2), 首先是 setState部分,看到这里接受两个参数partialState (局部状态,限定只有对象和函数可以作为第一个参数), callback
Component.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0; this.updater.enqueueSetState(this, partialState, callback, 'setState'); };
然后是更新部分enqueueSetState 函数
enqueueSetState: function (instance, partialState, callback) { var fiber = get(instance); callback = callback === undefined ? null : callback; { warnOnInvalidCallback$1(callback, 'setState'); } var expirationTime = computeExpirationForFiber(fiber); var update = { expirationTime: expirationTime, partialState: partialState, callback: callback, isReplace: false, isForced: false, capturedValue: null, next: null }; insertUpdateIntoFiber(fiber, update); scheduleWork(fiber, expirationTime); }
function insertUpdateIntoFiber(fiber, update) { ensureUpdateQueues(fiber); var queue1 = q1; var queue2 = q2; // Warn if an update is scheduled from inside an updater function. { if ((queue1.isProcessing || queue2 !== null && queue2.isProcessing) && !didWarnUpdateInsideUpdate) { warning(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' +
'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); didWarnUpdateInsideUpdate = true; } } // If there's only one queue, add the update to that queue and exit. if (queue2 === null) { insertUpdateIntoQueue(queue1, update); return; } // If either queue is empty, we need to add to both queues. if (queue1.last === null || queue2.last === null) { insertUpdateIntoQueue(queue1, update); insertUpdateIntoQueue(queue2, update); return; } // If both lists are not empty, the last update is the same for both lists // because of structural sharing. So, we should only append to one of // the lists. insertUpdateIntoQueue(queue1, update); // But we still need to update the `last` pointer of queue2. queue2.last = update; }
待续。。。
组件如下
import React, { Component } from 'react';
import './App.css';
class App extends Component {state = {count: 0}countChange = () => {this.setState({count: this.state.count + 1})this.setState({count: this.state.count + 1})console.log('count change')}countChange2 = () => {this.setState(preState => ({count: preState.count + 1}))this.setState(preState => ({count: preState.count + 1}))console.log('count change2')}UNSAFE_componentWillMount() {console.log('~~')}render() {return (<div className="App"><p>{this.state.count}</p><button onClick={this.countChange}>加一</button><button onClick={this.countChange2}>加一</button></div>);}}class App2 extends Component {render() {return <div><App></App></div>}}
export default App2;
测试中在setState中分别使用 对象参数和函数作为参数,结果说明 函数作为参数的方式是准确的,猜想,主要是对象的值已经确定了,而用使用函数是使用的preState作为参数,这个参数是在回调执行的时候传递下来的,所以是准确(在一个函数調用里面多次this.setState的情况下)。在第一种情况下面setState第二个参数是回调函数~在回调函数中使用this.state.count中获取也是对的。