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

How to watch only a single field in an object in useEffect hook?

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>
  );
};

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

出现警告是因为您在 useEffect 函数中使用了状态变量。仅当您不直接将状态变量用于任何事情时才会出现此警告。

执行此操作并进一步优化此代码的一种方法是使用 useCallback/useMemo。查看以下代码:

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

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

  const getCurrentLocale = useCallback(() => state.locale, [state.locale])

  useEffect(() => {
    const currentLocale = getCurrentLocale();
    saveLocale(currentLocale);
  }, [getCurrentLocale]);

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

使用上面的代码,您可以根据需要限制依赖项。

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

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