React-setState原理

1. state的定义

状态(state) 和 属性(props) 类似,都是一个组件所需要的一些数据集合,但是它是私有的,并且由组件本身完全控制,可以认为它是组件的“私有属性(或者是局部属性)”。
那我们如何改变这些“私有”的状态或者属性呢?React就引入了setState

2. setState的三个特性

a. 不要直接修改 state(状态)

例如:

this.state.comment = 'Hello';

此时,你虽然改变了this.state.comment的状态,但是改状态不会被重新渲染到组件上。
使用setState对this.state状态进行修改:

this.setState({
  comment: 'Hello'
});
b. setState可能是异步的

官方文档有说,setState更新可能是异步的,所以 this.props 和 this.state 可能是异步更新的,你不应该依靠它们的值来计算下一个状态。
怎样理解可能是异步这个概念呢?
阅读React的源码,我们了解到,setStated的执行原理:

setState执行过程

  • setState接收一个新的状态
  • 该接收到的新状态不会被立即执行么,而是存入到pendingStates(等待队列)中
  • 判断isBatchingUpdates(是否是批量更新模式)
    1>. isBatchingUpdates: true 将接收到的新状态保存到dirtyComponents(脏组件)中
    2>. isBatchingUpdates: false 遍历所有的dirtyComponents, 并且调用其 updateComponent方法更新pendingStates中的state 或者props。执行完之后,回将isBatchingUpdates: true。
c. state(状态)更新会被合并

当你调用 setState(), React 将合并你提供的对象到当前的状态中。所以当State是一个多键值的结构时,可以单独更新其中的一个,此时会进行“差分”更新,不会影响其他的属性值。

所以,setState并不是用异步的方式进行实现的,采用的是模拟异步的方式。即,setState可能是异步的。

一般我们会遇到这样的面试题:

this.setState({ number: this.state.number + 1 });
console.log(this.state);//0
this.setState({ number: this.state.number + 1 });
console.log(this.state);//0
setTimeout(() => {
      this.setState({ number: this.state.number + 1 });
      console.log(this.state);//2
      this.setState({ number: this.state.number + 1 });
      console.log(this.state);//3
}, 0);

为什么执行结果是 0 0 2 3 呢?
其实是,该代码在执行的时候,会先执行前4行同步代码,此时isBatchingUpdates: true,前两次执行的this.setState会被缓存到dirtyComponents中,所以前两次在打印状态的时候并没有改变状态值,打印结果为0。等同步代码执行完时,isBatchingUpdates: false,所以在执行setTimeout时,会先去遍历执行dirtyComponents,又因为state(状态)更新会被合并,所以其实前两次同步代码中对setState的执行被合并为一次,在执行到setTimeout里边的代码时,isBatchingUpdates已经为false,其this.setState会直接按顺序执行。固打印结果为 0 0 2 3。

3. 模拟源码实现setSate:

class Transaction {
    constructor(wrappers) {
        this.wrappers = wrappers;//{initialize,close}
    }
    perform(anyMethod) {
        console.log("this.wrappers:", this.wrappers);
        this.wrappers.forEach(wrapper => wrapper.initialize());
        anyMethod.call();
        this.wrappers.forEach(wrapper => wrapper.close());
    }
}
//batchingStrategy.isBatchingUpdates batchedUpdates
let batchingStrategy = {
    isBatchingUpdates: false,//默认是非批量更新模式
    dirtyComponents: [],// 脏组件 就组件的状态和界面上显示的不一样
    batchedUpdates() {
        this.dirtyComponents.forEach(component => component.updateComponent());
    }
}
class Updater {
    constructor(component) {
        this.component = component;
        this.pendingStates = [];
    }
    addState(partcialState) {
        this.pendingStates.push(partcialState);
        batchingStrategy.isBatchingUpdates
            ? batchingStrategy.dirtyComponents.push(this.component)
            : this.component.updateComponent()
    }
}
class Component {
    constructor(props) {
        this.props = props;
        this.$updater = new Updater(this);
    }
    setState(partcialState) {
        this.$updater.addState(partcialState);
    }
    updateComponent() {
        this.$updater.pendingStates.forEach(partcialState => Object.assign(this.state, partcialState));
        this.$updater.pendingStates.length = 0;
        let oldElement = this.domElement;
        let newElement = this.createDOMFromDOMString();
        oldElement.parentElement.replaceChild(newElement, oldElement);
    }
    //把一个DOM模板字符串转成真实的DOM元素
    createDOMFromDOMString() {
        //this;
        let htmlString = this.render();
        let div = document.createElement('div');
        div.innerHTML = htmlString;
        this.domElement = div.children[0];
        //让这个BUTTONDOM节点的component属性等于当前Counter组建的实例
        this.domElement.component = this;
        //this.domElement.addEventListener('click',this.add.bind(this));
        return this.domElement;
    }
    mount(container) {
        container.appendChild(this.createDOMFromDOMString());
    }
}
// 面向切片编程 AOP
let transaction = new Transaction([
    {
        initialize() {
            batchingStrategy.isBatchingUpdates = true;//开始批量更新模式
        },
        close() {
            batchingStrategy.isBatchingUpdates = false;
            batchingStrategy.batchedUpdates();//进行批量更新,把所有的脏组件根据自己的状态和属性重新渲染
        }
    }
]);
window.trigger = function (event, method) {
    let component = event.target.component;//event.target=this.domElement
    transaction.perform(component[method].bind(component));
}
class Counter extends Component {
    constructor(props) {
        super(props);
        this.state = { number: 0 }
    }

    add() {
        this.setState({ number: this.state.number + 1 });
        console.log(this.state);//0
        this.setState({ number: this.state.number + 2 });
        console.log(this.state);//0
        setTimeout(() => {

            this.setState({ number: this.state.number + 3 });
            console.log(this.state);//5
            this.setState({ number: this.state.number + 4 });
            console.log(this.state);//9
        }, 1000);
    }
    render() {
        return ``;
    }
}

你可能感兴趣的:(React-setState原理)