简体   繁体   English

在 React.useMemo 的依赖数组中放什么

[英]What to put in the dependency array in React.useMemo

Consider situation:考虑情况:

const App = ({ data = [], users = [] }) => {
  const selectedId = React.memo(() => {
    return data.find((id) => id === 'someId');
  }, [data]);

  const userIds = React.memo(() => {
    return users.map(({ id }) => id);
  }, [users]);

  const finalIds = React.memo(() => {
    return userIds.find((id) => id === selectedId);
  }, []);

  return finalIds.toString();
}

What should I put in the dependency array in finalIds ?我应该在finalIds的依赖数组中finalIds什么?

Should I:我是不是该:

  • provide the props used by variables that are used here, eg - [data, users]提供这里使用的变量使用的道具,例如 - [data, users]
  • provide the variables that are used here, eg - [selectedId, userIds]提供此处使用的变量,例如 - [selectedId, userIds]
  • keep it empty留空

You put any variables that you use inside the calculation.您可以将您使用的任何变量放入计算中。 In other words, [selectedId, userIds] .换句话说, [selectedId, userIds] When those variables change, you need to repeat the calculation, or finalIds will be stale.当这些变量发生变化时,您需要重复计算,否则finalIds将过时。

If you use eslint, i'd recommend using eslint-plugin-react-hooks .如果您使用 eslint,我建议您使用eslint-plugin-react-hooks It can spot if you're missing a variable from the dependency array and fill them in automatically.它可以发现您是否缺少依赖项数组中的变量并自动填充它们。

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

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