针对函数组件
背景:
当子组件的接收的props,前后对比没有改变时,不渲染组件。
Read/index.jsx
父组件
import React, { useState } from 'react';
import List from './components/List';
import Card from './components/Card';
import './index.scss';
export default function Read(pros) {
console.log('redner-read');
const [list1, setList1] = useState(0);
const [card1, setCard1] = useState(0);
const [card2, setCard2] = useState(0);
const cardGetCount1 = (value) => {
setCard1(value)
}
const cardGetCount2 = (value) => {
setCard2(value)
}
const listGetCount1 = (value) => {
setList1(value)
}
return (
<>
<div className='top_READ'>
<h2> Read</h2>
<List
value1={list1}
listGetCount1={listGetCount1}
/>
<br />
<Card
value1={card1}
value2={card2}
cardGetCount1={cardGetCount1}
cardGetCount2={cardGetCount2}
/>
</div>
</>
)
}
List/index.jsx
子组件
import React, { useState, memo } from 'react';
import Button from '../../../../components/Button';
const areEqual = (prevProps, nextProps) => {
if (prevProps?.value1 === nextProps?.value1) {
return true
}
return false
}
function List(props) {
const {
value1 = 0,
listGetCount1,
} = props;
console.log('List', props);
const [count1, setCount1] = useState(value1);
const handleCount1 = () => {
setCount1(count1 + 1)
listGetCount1(count1 + 1)
}
return (
<>
<ul>
<li>
<Button type="primary" onClick={handleCount1}>
Listchange1
</Button>
</li>
</ul>
</>
)
}
export default memo(List,areEqual )
Card/index.jsx
子组件
import React, { useState, memo } from 'react';
import Button from '../../../../components/Button';
const areEqual = (prevProps, nextProps) => {
if (prevProps?.value1 === nextProps?.value1 &&
prevProps?.value2 === nextProps?.value2) {
return true
}
return false
}
function Card(props) {
const {
value1 = 0,
value2 = 0,
cardGetCount1,
cardGetCount2
} = props;
console.log('Card', props);
const [count1, setCount1] = useState(value1);
const [count2, setCount2] = useState(value2);
const handleCount1 = () => {
setCount1(count1 + 1)
cardGetCount1(count1 + 1)
}
const handleCount2 = () => {
console.log('handleCount2');
setCount2(count2 + 1)
cardGetCount2(count2 + 1)
}
return (
<>
<ul>
<li>
<Button type="primary" onClick={handleCount1}>
Cardchange1
</Button>
</li>
<li>
<Button type="primary" onClick={handleCount2}>
Cardchange2
</Button>
</li>
</ul>
</>
)
}
export default memo(Card, areEqual)