Deep In React (一) 高性能React组件
React的渲染机制 在React内部,存在着初始化渲染和更新渲染的概念。 初始化渲染会在组件第一次挂载时,渲染所有的节点 当我们希望改变某个子节点时 我们所期望React帮我们实现的渲染行为是这样的 我们希望当我们的props向下传递时,只有对应需要更新的节点进行更新并重新渲染,其余节点不需要更新和重新渲染。 但是事实上,在默认的情况下,结果却是这样的 所有的组件树都被重新渲染,因为对于React而言,只要有props或者state发生了改变,我的组件就要重新渲染,所以除了绿色的节点,所有的黄色节点也被渲染了。 例子: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 const Foo = ({foo}) => { console.log('Foo is rendering!'); return (<div>Foo {foo}</div>); } const Bar = ({bar}) => { console.log('Bar is rendering!'); return (<div>Bar {bar}</div>); } const FooBarGroup = ({foo, bar}) => { console.log('FooBar is rendering!'); return ( <div> <Foo foo={foo} /> <Bar bar={bar} /> </div> ) } class App extends React.Component { constructor(props) { super(props) this.state = { foo: 0, bar: 0 }; this.handleFooClick = this.handleFooClick.bind(this); this.handleBarClick = this.handleBarClick.bind(this); } handleFooClick (e) { e.preventDefault(); const newFoo = this.state.foo + 1; this.setState({foo: newFoo}); } handleBarClick(e) { e.preventDefault(); const newBar = this.state.bar + 1; this.setState({bar: newBar}); } render() { const {foo, bar} = this.state; return ( <div className="App"> <button onClick={this.handleFooClick}>Foo</button> <button onClick={this.handleBarClick}>Bar</button> <FooBarGroup foo={foo} bar={bar} /> </div> ); } } ...