簡體   English   中英

React-Error:重新渲染太多。 React 限制渲染次數以防止無限循環

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

我想出了一個錯誤,

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

在 function 上,從 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 以解決此問題。

感謝您的任何幫助。

考慮不要將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

暫無
暫無

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

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