如何在 useEffect 挂钩中仅观察对象中的单个字段?

Hen*_*aye 5 reactjs react-hooks

export const LocaleProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, { locale: DEFAULT_LOCALE });

  useEffect(() => {
    const storedLocale = getStoredLocale();
    if (storedLocale) dispatch(changeLocale(storedLocale));
  }, []);

  useEffect(() => {
    const { locale: currentLocale } = state;
    saveLocale(currentLocale);
  }, [state, state.locale]);

  return (
    <LocaleContext.Provider value={[state, dispatch]}>
      {children}
    </LocaleContext.Provider>
  );
};
Run Code Online (Sandbox Code Playgroud)

如何仅观察对象状态中的单个字段。正如你在第二个效果中看到的,当我只观看 [state.locale] 时,我的 VS 代码显示 eslint 警告(react-hook/exhaustive-deps),React Hook useEffect 缺少依赖项:“state”。包含它或删除依赖项数组。当我保存代码时,VS 代码会在依赖项数组 ([state, state.locale]) 中添加状态。

Apr*_*ion 4

不够react-hook/exhaustive-deps聪明,无法识别只需要对象的某些属性,它关注的是依赖变量列表(在 内部使用的变量)useEffect,因此我们可以通过提取变量来配合规则:

const { locale: currentLocale } = state;
useEffect(() => {
  saveLocale(currentLocale);
}, [currentLocale]);
Run Code Online (Sandbox Code Playgroud)