【问题标题】:Maximum update depth exceeded in useFocusEffectuseFocusEffect 超出最大更新深度
【发布时间】:2021-12-28 23:50:04
【问题描述】:

我正在运行 useFocusEffect 进行 API 调用(使用 reactQuery),但出现此错误:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

这是引发错误的具体代码,我不知道错误是来自 reactQuery useMutation 还是来自 react 导航的 useFocusEffect

export const OrderStatementLoading = () => {
  const {  
    mutateAsync: createSchedulePayment,
    isLoading: isLoadingSave,
    isSuccess: isSuccessSave,
    reset,
  } = useMutation(//...useMutationParams);

  useFocusEffect(
    useCallback(() => {
      createSchedulePayment()
        .then(() => console.log('success'))
        .catch(() => console.log('error'))
        .finally(() => {
          reset();
        });
    }, [reset, createSchedulePayment]),
  );

  return {// redered content}
};```

【问题讨论】:

    标签: reactjs react-native react-navigation react-query


    【解决方案1】:

    useMutation返回的函数是引用稳定的,所以你可以把它们放在useEffect的依赖数组中。

    我很快在代码盒中尝试了这个,效果很好:

      const { mutateAsync, reset } = useMutation(() => Promise.resolve(5));
      React.useEffect(() => {
        mutateAsync()
          .then(() => {
            console.log("success");
          })
          .then(() => reset());
      }, [mutateAsync, reset]);
    
    

    https://codesandbox.io/s/usemutation-effect-4f3r6

    所以我认为这一定与useFocusEffectuseCallback 一起工作的方式有关?

    你链接到的文档说:

    useFocusEffect 类似于 React 的 useEffect 钩子。唯一的区别是它仅在屏幕当前聚焦时运行。

    如果这是真的,我想知道为什么需要 useCallback 而不是将依赖项直接传递给 useFocusEffect... 不过明确提到了:

    注意:为避免过于频繁地运行效果,重要的是在将回调传递给 useFocusEffect 之前将回调包装在 useCallback 中,如示例所示。

    而且source还指定了你传递的函数as a dependency to useEffect,所以看来useCallback确实是必要的。

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      相关资源
      最近更新 更多