簡體   English   中英

如何解決`react-hooks/exhaustive-deps`的`React Hook useEffect缺少依賴`?

[英]How to solve `React Hook useEffect has a missing dependency` of `react-hooks/exhaustive-deps`?

我在這里詢問有關react hooks缺失依賴項的一些問題

我盡量簡潔,這是我的控制台中的警告消息

Compiled with warnings.

./src/views/categories/Categories.tsx
  Line 14:6:  React Hook useEffect has a missing dependency: 'dispatcher'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

鈎子useEffect的代碼

const [categoriesList, dispatcher] = useCategoryList({})

useEffect(() => {
  !isOpenConfirmAddModal && dispatcher.fetchCategories()
}, [isOpenConfirmAddModal])

這是自定義鈎子useCategoryList的代碼

export const useCategoryList = (
  initialState: CategoriesData
): CategoriesListHook => {
  const [state, dispatch] = useReducer(categoryReducer, initialState)

  const fetchCategories = async () => {
    const categories = await getCategories()
    dispatch({ type: FETCH_CATEGORIES, data: categories })
  }

  // ....

  return [
    state,
    {
      fetchCategories
      // ...
    }
  ]
}

如果我將調度程序設置為依賴項

useEffect(() => {
  !isOpenConfirmAddModal && dispatcher.fetchCategories()
}, [isOpenConfirmAddModal, dispatcher])

並且應用程序中的效果是調用dispatcher.fetchCategories()一個永恆循環,似乎dispatch不斷更新自身並且循環永無止境。

我嘗試了 SO 中建議的其他一些嘗試,但我從未在useEffect 中看到來自useReducer調度程序

想法,謝謝!

在您的自定義鈎子中,您不能使用 useMemo 重新創建 fetchCategories 和可能的其他方法:

export const useCategoryList = initialState => {
  const [state, dispatch] = useReducer(
    categoryReducer,
    initialState
  );

  const methods = React.useMemo(
    () => ({
      fetchCategories: async () => {
        const categories = await getCategories();
        dispatch({
          type: FETCH_CATEGORIES,
          data: categories,
        });
      },
      //other methods
    }),
    []//no dependencies
  );

  return [state, methods];
};

現在 fetchCategies 在組件生命周期中不應更改,因此您可以執行以下操作:

const [categoriesList, {fetchCategories}] = useCategoryList({});
useEffect(() => {
  !isOpenConfirmAddModal && fetchCategories();
}, [fetchCategories]);

您可以在自定義鈎子本身內部使用useCallback來包裝fetchCategories方法,從而提供其自己的依賴項數組。

const fetchCategories = useCallback(async () => {
  const categories = await getCategories()
  dispatch({ type: FETCH_CATEGORIES, data: categories })
},[<your dependencies>])
// check and update this dependency array

我認為這是更抽象的方式來做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM