File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- import React from 'react' ;
21import ReactDOM from 'react-dom/client' ;
32import App from "./App" ;
43
Original file line number Diff line number Diff line change 1+ import React , { useState } from 'react' ;
2+ import A from "./components/A" ;
3+
4+ /**
5+ * React.memo() 一个高阶组件,用于缓存组件
6+ * 接收一个组件作为参数,并返回一个包装过的新组件,只有组件的props发生变化才会触发渲染
7+ */
8+
9+ const App = ( ) => {
10+ const [ count , setCount ] = useState ( 1 ) ;
11+ const clickHandler = ( ) => {
12+ setCount ( prevState => prevState + 1 ) ;
13+ } ;
14+
15+ return (
16+ < div >
17+ < h2 > App - { count } </ h2 >
18+ < button onClick = { clickHandler } > App 不触发A渲染</ button >
19+ < A />
20+ </ div >
21+ ) ;
22+ } ;
23+
24+ export default App ;
Original file line number Diff line number Diff line change 1+ import React , { useState } from 'react' ;
2+ import B from "./B" ;
3+
4+ const A = ( ) => {
5+ console . log ( 'A渲染' ) ;
6+
7+ const [ count , setCount ] = useState ( 1 ) ;
8+ const clickHandler = ( ) => {
9+ setCount ( prevState => prevState + 1 ) ;
10+ } ;
11+
12+ const test = count % 4 === 0 ;
13+
14+ return (
15+ < div >
16+ < h2 > 组件A - { count } </ h2 >
17+ < button onClick = { clickHandler } > %4触发B渲染</ button >
18+ < B test = { test } />
19+ </ div >
20+ ) ;
21+ } ;
22+
23+ export default React . memo ( A ) ;
Original file line number Diff line number Diff line change 1+ import React from 'react' ;
2+
3+ const B = ( props ) => {
4+ console . log ( 'B渲染' ) ;
5+
6+ return (
7+ < div >
8+ < h2 > 组件B</ h2 >
9+ < p > { props . test && 'test' } </ p >
10+ </ div >
11+ ) ;
12+ } ;
13+
14+ export default React . memo ( B ) ;
Original file line number Diff line number Diff line change 1+ import ReactDOM from 'react-dom/client' ;
2+ import App from "./App" ;
3+
4+ const root = ReactDOM . createRoot ( document . getElementById ( 'root' ) ) ;
5+ root . render ( < App /> ) ;
You can’t perform that action at this time.
0 commit comments