react Hooks —— memo用法
2022-08-25 本文已影响0人
sweetylulu
改变Parent组件中的num,会重新渲染Child组;改变Parent组件中的count,不会重新渲染Child组件
import React, { useEffect, useState, useRef, memo } from "react";
const Child = memo(
({ num }) => {
console.log('子组件')
return <div>子组件 {num}</div>;
}
);
const Parent = () => {
let timer = useRef(null);
const [count, setCount] = useState(0);
const [num, setNum] = useState(1);
useEffect(() => {
timer.current = setInterval(() => {
setCount((c) => c + 1);
}, 3000);
return () => {
clearInterval(timer.current);
};
}, []);
return (
<div>
<Child num={num} />
<button onClick={() => setNum(num + 1)}>修改num,num当前值:{num}</button>
<h1>首页 {count}</h1>
</div>
);
}
export default Parent