反应错误:重新渲染太多。 React 限制渲染次数以防止无限循环

时间:2021-04-05 02:40:18

标签: javascript reactjs axios

我想出了一个错误,

Error: Too many re-renders. React limits
the number of renders to prevent an infinite loop.

关于从 axios 获取 api 数据的函数。这是我第一次出现这个错误。

加载页面时出现错误。

根据反应,罪魁祸首可能在这个 useEffect 中。

useEffect(() => {
  axiosInstance.get('all/buckets/').then((res) => {
    const allBuckets = res.data;
    setAppState({ loading: false, buckets: allBuckets });
    console.log(res.data);
  });
}, [setAppState]);

这里是完整的组件:

export default function GetUserBuckets() {
  const classes = useStyles();
  const ListLoading = LoadingComponent(UserBuckets);
  const [appState, setAppState] = useState({
    loading: true,
    posts: null,
  });

  useEffect(() => {
    axiosInstance.get('all/buckets/')
      .then((res) => {
        const allBuckets = res.data;
        setAppState({
          loading: false,
          buckets: allBuckets,
        });
        console.log(res.data);
      });
  }, [setAppState]);

  return (
    <div className={classes.text}>
      <h1>Buckets</h1>
      <ListLoading
       isLoading={appState.loading}
       buckets={appState.buckets}
      />
      <Container className={classes.createBucket}>
        <CreateDialog />
      </Container>
    </div>
  );
}

错误也很不一致,有时出现有时不出现,基于用户请求数据。这可能是后端问题,但目前正在尝试查看是否可以更好地整理我的 useEffect 以解决此问题。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

考虑不要将 setAppState 作为依赖项传递给您的 useEffect 钩子。

只需使用一个空数组,这样它只会在您的 GetUserBuckets 组件被挂载时运行一次。

重构你的 useEffect 看起来像这样

useEffect(() => {
  axiosInstance.get('all/buckets/').then((res) => {
    const allBuckets = res.data;
    setAppState({ loading: false, buckets: allBuckets });
    console.log(res.data);
  };
}, []); // Removed the setAppState here