代码如下,请问在只更新 Box1 的 count 的值时,如何避免 Box2,Box3,Box4 的重复渲染?
import React, { memo, useCallback, useContext, useRef } from "react";
const Context = React.createContext<any>({});
export default function App() {
const [count, setCount] = React.useState(0);
const [flag, setFlag] = React.useState(false);
const add = useCallback(() => setCount((v) => v + 1), []);
const toggle = useCallback(() => setFlag((v) => !v), []);
const contextValue = { count, add, flag, toggle };
return (
<Context.Provider value={contextValue}>
<Box1 />
<Box2 />
<Box3 />
<Box4 />
</Context.Provider>
);
}
const Box1 = memo(() => {
const { count } = useContext(Context);
const ref = useRef(true);
ref.current = !ref.current;
return (
<div className="box" style={{ backgroundColor: ref.current ? "white" : "gray" }}>
Box1 count:{count}
</div>
);
});
const Box2 = memo(() => {
const { flag } = useContext(Context);
const ref = useRef(true);
ref.current = !ref.current;
return (
<div className="box" style={{ backgroundColor: ref.current ? "white" : "gray" }}>
Box2 flag:{flag}
</div>
);
});
const Box3 = memo(() => {
const { add } = useContext(Context);
const ref = useRef(true);
ref.current = !ref.current;
return (
<div className="box" onClick={add} style={{ backgroundColor: ref.current ? "white" : "gray" }}>
Box3 add
</div>
);
});
const Box4 = memo(() => {
const { toggle } = useContext(Context);
const ref = useRef(true);
ref.current = !ref.current;
return (
<div className="box" onClick={toggle} style={{ backgroundColor: ref.current ? "white" : "gray" }}>
Box4 toggle
</div>
);
});
确实有一些问题,把state 和 actions 分开这个会好一点:
用 useMemo:
拆分 Context: