简体   繁体   English

我可以在 useMemo 中安全导航吗

[英]Can I safe navigate within useMemo

Can I use the && style safe navigation or lodash get in useMemo's second parameter like this:get在 useMemo 的第二个参数中使用&&样式的安全导航或 lodash get ,如下所示:

useMemo(() => {
  return {
    ...
  }
}, [state && state.data])  // or with lodash: get(state, 'data')

Yes, but not without warning.是的,但并非没有警告。

React Hook useMemo has a complex expression in the dependency array. React Hook useMemo 在依赖数组中有一个复杂的表达式。 Extract it to a separate variable so it can be statically checked.将其提取到一个单独的变量中,以便对其进行静态检查。 (react-hooks/exhaustive-deps)eslint (react-hooks/exhaustive-deps)eslint

export default function App() {
  const [state, setState] = useState({ data: 'foobar' });

  const memoizedState = useMemo(() => {
    return state.data + state.data;
  }, [state && state.data]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{memoizedState}</h2>
    </div>
  );
}

编辑 festive-wozniak-z80q5

Better solution would be to factor it into a single variable as suggested, or use the entire state value and handle it internally.更好的解决方案是按照建议将其分解为单个变量,或者使用整个状态值并在内部处理它。 Keep in mind the more you minimize the surface area of reference mutations then the more stable your memoized value will be.请记住,参考突变的表面积越小,您的记忆值就越稳定。

If you are certain a state value like this will always have that shape, then I think you can safely use state.data as a dependency.如果您确定这样的状态值将始终具有该形状,那么我认为您可以安全地使用state.data作为依赖项。

I generally prefer NOT to use complex objects in react useState hooks (you certainly can) and will break the object properties into their own state hooks.我通常喜欢在 react useState hooks 中使用复杂的对象(你当然可以)并且会将对象属性分解为它们自己的状态钩子。 This allows you to update "parts" of your state without mutating references to the rest.这允许您更新状态的“部分”而不会改变对其余部分的引用。 This is especially advantageous in situations like yours where maybe you're not sure state.abcdata is a complete and valid defined object reference.这在您可能不确定state.abcdata是否是完整且有效的已定义对象引用的情况下尤其有利。 Or some other hooks depend only on part of your component state.或者其他一些钩子依赖于你的组件状态的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM