gpt4 book ai didi

reactjs - 确保路径由变量定义的嵌套字段在添加到依赖项数组时触发 React.useMemo 更新

转载 作者:行者123 更新时间:2023-12-05 06:09:17 25 4
gpt4 key购买 nike

我使用 TypeScript 4 和 React 17

我在自定义钩子(Hook)中有这段代码:

  const myValue = useMemo((): string[] => {
if (someCondition) {
return (myMap?.field && myMap.field.[subfieldId]) || null
} else {
...
}
}, [myMap.field.[subfieldId]])

ESlint 提示 myMap.field.[subfieldId] 必须移动到一个变量中才能以编程方式进行检查。

所以我改成这样:

  const currentData: string[] | null = (myMap?.field && myMap.field.[subfieldId]) || null

const myValue = useMemo((): string[] => {
if (someCondition) {
return currentData
} else {
...
}
}, [currentData])

我不确定让变量在上层作用域中,在每次渲染时重新计算是一个好习惯,我什至担心会产生无限循环。

ESLInt 建议我改为这样做,这要简单得多:

  const myValue = useMemo((): string[] => {
if (someCondition) {
return (myMap?.field && myMap.field.[subfieldId]) || null
} else {
...
}
}, [myMap.field])

myMap.field 是否足以让 React 发现 myMap.field[subfieldId] 发生变化?我想应该是。事实上,如果我只放 myMap,React 将不知道发生了什么变化,因为对象引用本身并没有改变,但是当比较之前和新的 myMap.field 时,React 会检查所有的子字段。是吗?

最佳答案

根据 react hook linter:

React Hook React.useMemo has an unnecessary dependency: 'myMap'. Either exclude it or remove the dependency array. Outer scope values like 'myMap' aren't valid dependencies because mutating them doesn't re-render the component. (react-hooks/exhaustive-deps)

所以你应该没问题:

const myValue = useMemo((): string[] => {
if (someCondition) {
return myMap?.field[subfieldId] || null
} else {
// ...
}
}, [subfieldId]);

关于reactjs - 确保路径由变量定义的嵌套字段在添加到依赖项数组时触发 React.useMemo 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64884423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com