[英]Leave useEffect empty dependency giving eslint error
I have a small problem.我有一个小问题。 And Here is how I want the code to behave.
这就是我希望代码的行为方式。
when the component is mounted call the useEffect only once, but inside the useEffect I am using a value from redux store which require to put in dependancy, which causing an infinit loop当安装组件时只调用一次 useEffect,但在 useEffect 中我使用的是 redux 存储中的一个值,它需要依赖,这会导致无限循环
So how do I save the call function only once in the component without useEffect and avoid the infinite loop, or is there another way那么如何在没有 useEffect 的组件中仅保存一次调用 function 并避免无限循环,或者还有另一种方法
Also If I write the logic in a function, it requires the function to be callback and I face the same issue另外,如果我在 function 中编写逻辑,它需要 function 进行回调,我面临同样的问题
Here is my implementation:这是我的实现:
const { price = { min: 5000 } } = useSelector(selectPendingPost);
const savePrice = useCallback(
(value) => {
dispatch(
addFieldsToPendingPost({
price: { min: value[0], ...(value[1] && { max: value[1] }) },
})
);
},
[dispatch]
);
useEffect(() => {
savePrice([price.min]);
}, [savePrice]);
Have you tried to add price.min
as dependency?您是否尝试将
price.min
添加为依赖项? price
is an object and is recreated everytime. price
是 object,每次都会重新创建。 But price.min
seems like it's a number, so the dependency will compare its value and this should be constant after the first call of useEffect
但是
price.min
看起来像是一个数字,所以依赖项会比较它的值,并且在第一次调用useEffect
之后这应该是常量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.