【发布时间】:2021-10-11 12:53:42
【问题描述】:
我正在开发一个大型 React 应用程序,其中性能至关重要,不必要的重新渲染代价高昂。
我有以下例子:
const CounterContext = React.createContext();
const CounterProvider = ({children}) => {
const [counterA, setCounterA] = React.useState(0);
const [counterB, setCounterB] = React.useState(0);
return (
<CounterContext.Provider value={{counterA, counterB}}>
{children}
<button onClick={() => setCounterA(counterA + 1)}>Counter A ++</button>
<button onClick={() => setCounterB(counterB + 1)}>Counter B ++</button>
<button onClick={() => {setCounterA(0); setCounterB(0)}}>reset</button>
</CounterContext.Provider>
)
}
const CounterA = () => {
const value = React.useContext(CounterContext);
console.log('CounterA re-render');
return <p>Counter A: {value.counterA}</p>;
}
const CounterB = () => {
const value = React.useContext(CounterContext);
console.log('CounterB re-render');
return <p>Counter B: {value.counterB}</p>;
};
const App = () => {
return (
<CounterProvider>
<CounterA />
<CounterB />
</CounterProvider>
)
};
jsfiddle:https://jsfiddle.net/mitchkman/k3hm0vfq/1/
单击 CounterA 按钮时,两个 CounterA 和 CounterB 组件将重新渲染。如果value 中的counterA 属性发生变化,我只想重新渲染CounterA。
我还希望能够为条件重新渲染提供某种形式的灵活性。这是我正在尝试做的伪代码:
const MyComponent = () => {
// Only re-render MyComponent if value.property equals 42
const value = useContext(MyContext, (value) => value.property === 42);
...
};
【问题讨论】:
-
您想尝试阻止
CoutnerA的任何重新呈现,还是在满足谓词(即counterA === 42)之前不暴露更新的counterA状态值? “如果值中的 counterA 属性发生变化,我只想重新渲染 CounterA。”这就是开箱即用的工作方式。如果您不希望CounterA由于其他原因重新渲染,请使用memo高阶组件并传递自定义areEqual函数。
标签: javascript reactjs publish-subscribe react-context