vue和react都使用了虛擬DOM,其中一個優點就是通過diff算法只更新部分組件,提升了DOM重繪性能。網上有些人說vue只更新變化的組件,而react更新所有組件,這樣的話react的diff算法是擺設嗎,實際情況是怎樣的?下面我們來一探究竟。
Vue組件更新
下面來測試一下Vue組件data更新會影響哪些組件。定義了三層組件,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時,打印結果如下:
再測試一下更新父組件傳給給子組件的props時的情況:
<Two :user-name="userName"/> <button @click="modifyProps">更改傳遞給子組件的props</button> modifyProps() { this.userName = 'gao'; },
當更新userName時子組件情況如下:
可見父子組件都更新了。
vue總結:
1.當更新父組件data中的數據時,其自身組件更新,其子組件(無限遞歸)不會更新
2.更新某個組件data中的數據時,其兄弟組件不更新
3.當更新子組件data中的數據時,父組件不更新
4.當更新父組件傳遞給子組件的props變化時,子組件(第一級子組件)更新。
注:這些測試都是數據在html中被使用的前提下,如果數據在html中未使用,update不會更新。
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組件data更新只更新自己,react組件state更新會更新自己及所以有子組件。
測試代碼詳見:https://github.com/dxdleikai/vueCompoenentUpdate https://github.com/dxdleikai/reactComponentUpdate