Skip to content

Commit 34f9200

Browse files
author
victorsun
committed
upd: react
1 parent 0087dd8 commit 34f9200

5 files changed

Lines changed: 66 additions & 1 deletion

File tree

12-前端框架/03-React/react18/12-reducer/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import React from 'react';
21
import ReactDOM from 'react-dom/client';
32
import App from "./App";
43

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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;
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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);
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
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/>);

0 commit comments

Comments
 (0)