针对函数组件
背景:
当子组件的接收的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)
今天的文章react 子组件_caddy和nginx性能对比分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/89462.html