[英]How to use useMemo replacing useEffect?
I have options array for month and I am using it in useEffect
but getting warning for deps.我有一个月的选项数组,我在
useEffect
中使用它,但收到了对 deps 的警告。 Kindly guide how to use useMemo
.请指导如何使用
useMemo
。 I am getting warning as given below: The 'options' array makes the dependencies of useEffect
Hook (at line 83) change on every render.我收到如下警告:'options' 数组使
useEffect
Hook(第 83 行)的依赖关系在每次渲染时都发生变化。 To fix this, wrap the initialization of 'options' in its own useMemo
Hook react-hooks/exhaustive-deps要解决此问题,请将“选项”的初始化包装在其自己的
useMemo
Hook react-hooks/exhaustive-deps 中
const options = [];
useEffect(() => {
if (financialMonth) {
options.forEach((item) => {
if (Number(item.value) === Number(financialMonth)) {
setMonthDefault(item.text);
}
});
if (financialMonth.length === 0) setMonthDefault("April");
}
}, [financialMonth, options]);
Simply:简单地:
const options = useMemo(() => [], [])
If you have a constant array of values (if it does not depend on state or props), then consider putting it outside of the component.如果你有一个常量数组(如果它不依赖于 state 或道具),那么考虑将它放在组件之外。 That way you won't have to worry about
useMemo
or having it in the useEffect
dependency array.这样您就不必担心
useMemo
或将它放在useEffect
依赖数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.