Daily Notes

Just Some Notes

  • React中setState方法的同步与异步

    this.setState方法内部做了什么?

    调用this.setState方法后,先进行状态合并,并会触发状态更新,重新调用组件的render方法,render方法执行结束后会产生新的虚拟dom,最后React内部会对组件的新旧虚拟dom进行diff操作,得到针对旧虚拟dom的patch,最后根据patch来更新dom结构,实现视图更新.

    this.setState的同步和异步,为什么这样处理?

    React的setState方法本质上都是同步操作,所谓异步,指的是将一系列的setState操作先收集起来,最终在函数执行结束时进行状态合并后再进行批量执行.

    之所以这样做,是因为如前文所述,每次调用setState方法都会触发视图更新,先将多次setState的调用收集起来,最终根据每次setState调用的状态参数进行状态合并后会得到最终的组件状态,这样一来,虽然调用了多次this.setState,但最终只会调用一次组件的render方法,视图也只会更新一次.

    阅读全文
  • script标签的async和defer属性

    首先,async和defer属性的作用都是指示浏览器加载外联脚本的具体方式,所以两个属性都必须用在外联脚本的script的标签上,否则无效.

    <script src="./a.js" async></script>
    <script src="./b.js" defer></script>
    

    不使用async和defer

    正常情况下,script标签会阻塞浏览器对HTML文档的解析,遇到script标签,浏览器会遵循下列步骤:
    下载脚本 → 运行脚本 → 继续解析后面的文档内容.

    async

    阅读全文
  • js中的对象继承方式以及优劣对比分析

    原型链继承

    // 父类构造函数
    function Parent() {
        this.name = 'John';
        this.habits = ['basketball', 'cook', 'boxing'];
    }
    // 父类原型
    Parent.prototype.sayHello = function sayHello() {
        console.log('hello, world');
    }
    // 子类构造函数
    function Child() {
        // @empty
    }
    // 将子类的原型指向父类的一个实例
    Child.prototype = new Parent();
    
    const child_1 = new Child();
    console.log(child_1.name); // John
    console.log(child_2.habits); // ['basketball', 'cook', 'boxing']
    const child_2 = new Child();
    console.log(child_1.habits === child_2.habits); // true
    child_1.habits.push('running');
    console.log(child_1.habits); // ['basketball', 'cook', 'boxing', 'running']
    

    缺点:父类实例中的引用类型对象由所有的子类实例共享,只要其中一个子类实例对其进行了修改,便会影响其他子类实例,容易“牵一发动全身”,造成容易忽略的BUG.

    构造函数继承

    function Parent(name) {
        this.name = name;
        this.habits = ['boxing'];
        this.sayHello = function sayHello() {
            console.log('hello, world!');
        }
    }
    
    function Child() {
        Parent.call(this, 'frank');
    }
    
    const child_1 = new Child();
    const child_2 = new Child();
    child_1.habits.push('cooking');
    console.log(child_1.habits); // ['boxing', 'cooking']
    console.log(child_2.habits); // ['boxing']
    console.log(child_1.sayHello === child_2.sayHello); // false
    
    阅读全文