[英]React Hooks: Why does the exhaustive-deps linter rule want a local function used in useMemo in the dependency list?
If I use a local function in the function I pass to useMemo
(or other hooks), the exhaustive-deps linter rule wants the local function in the dependency list of useMemo
.如果我在传递给
useMemo
(或其他钩子)的函数中使用本地函数,则详尽的 deps linter 规则希望在useMemo
的依赖项列表中使用本地函数。 I understand that with each render, the local function is a new instance.我知道每次渲染时,本地函数都是一个新实例。 But since it never really changes, in my opinion it's unnecessary to put in in the dependency list, particularly because then I need to use
useCallback
for the function (what makes the code more complicated).但是因为它从来没有真正改变过,所以我认为没有必要放在依赖列表中,特别是因为我需要对函数使用
useCallback
(这使得代码更复杂)。
Here is a working example:这是一个工作示例:
const [inputNumber, setInputNumber] = useState(35);
function calculateFibonacciNumber(number) {
return number < 1 ? 0 : number <= 2 ? 1
: calculateFibonacciNumber(number - 1) + calculateFibonacciNumber(number - 2);
};
const fibonacciNumber = useMemo(() => {
return calculatedFibonacciNumber = calculateFibonacciNumber(inputNumber);
}, [inputNumber]); // Here the exhaustive-deps rule wants calculateFibonacciNumber in the dependency list
So, is there a real reason why calculateFibonacciNumber
should be placed in the dependency list (via useCallback
)?那么,为什么应该将
calculateFibonacciNumber
放在依赖项列表中(通过useCallback
)有真正的原因吗?
I guess the reason behind that is you are using calculateFibonacciNumber
outside still of useMemo
.我猜这背后的原因是您在
useMemo
之外仍然使用calculateFibonacciNumber
。
Maybe you could try to move the definition inside, just like this:也许您可以尝试将定义移到里面,就像这样:
const fibonacciNumber = useMemo(() => {
function calculateFibonacciNumber(number) {
return number < 1 ? 0 : number <= 2 ? 1
: calculateFibonacciNumber(number - 1) + calculateFibonacciNumber(number - 2);
};
return calculatedFibonacciNumber = calculateFibonacciNumber(inputNumber);
}, [inputNumber]);
In this case you won't see that warning message.在这种情况下,您不会看到该警告消息。
I hope that helps!我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.