Vue和React组件diff更新影响范围对比

vue和react都使用了虚拟DOM,其中一个优点就是通过diff算法只更新部分组件,提升了DOM重绘性能。网上有些人说vue只更新变化的组件,而react更新所有组件,这样的话react的diff算法是摆设吗,实际情况是怎样的?下面我们来一探究竟。

Vue组件更新

下面来测试一下React组件state更新会影响哪些组件。定义了三层组件,APP > [Two、TwoBrother]  > Three, 最下图:

组件Two的代码如下:

<template>
  <div>
    <p>组件Two two_number = [{{two_number}}] <button @click="twoNumberAdd">two_number + 1</button></p>
    <div class="three">
      <Three />
    </div>
  </div>
</template>

<script>
import Three from './Three.vue'
export default {
  name: 'Two',
  components: {
    Three
  },
  data() {
    return {
      two_number: 1
    }
  },
  methods: {
    twoNumberAdd() {
      this.two_number += 1;
    }
  },
  updated() {
    console.log('component two update');
  }
}
</script>

当更新组件two two_number时,打印结果如下:

当更新组件app app_number时,打印结果如下:

vue总结:

1.当更新父组件data中的数据时,其自身组件更新,其子组件(无限递归)不会更新

2.更新某个组件,其兄弟组件不更新

3.当更新子组件,父组件不更新

 

 

 

React组件更新

下面来测试一下React组件state更新会影响哪些组件。定义了三层组件,APP > [Two、TwoBrother]  > Three, 最下图:

组件Two代码如下:

class Two extends React.Component {
    state = {
        two_number: 1
      }
    twoNumberAdd = () => {
        this.setState({
            two_number: this.state.two_number + 1
        });
      }
      componentDidUpdate() {
        console.log('compoent two update');
      }
    render() {
        return (
            <div>
                <p>
                组件Two。two_number = [{this.state.two_number}] <button onClick={this.twoNumberAdd}>two_state_number + 1</button>
            </p>
            <div className="three">
                <h4>组件two的子组件</h4>
             <Three></Three>
            </div>
            </div>
        )
    }
}

当更新组件Two的state two_number时,打印结果如下:

当更新APP的state app_number时,打印结果如下:

react总结:

1.当更新父组件state中的数据时,其自身组件及所有子组件(无限递归)都会更新

2.更新某个组件,其兄弟组件不更新

3.当更新子组件,父组件不更新

总结

通过vue和react组件更新对比,可以看出他们的区别:

vue组件更新只更新自己,react组件更新会更新自己及所以有子组件。

测试代码详见:https://github.com/dxdleikai/vueCompoenentUpdate   https://github.com/dxdleikai/reactComponentUpdate

猜你喜欢

转载自www.cnblogs.com/bagexiaowenti/p/13163245.html