[英]React-Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
I'm coming up with an error,我想出了一个错误,
Error: Too many re-renders. React limits
the number of renders to prevent an infinite loop.
on a function that GETS api data from axios.在 function 上,从 axios 获取 api 数据。 This is the first time this error is showing up for me.
这是我第一次出现这个错误。
The errors show up when I'm loading the page.当我加载页面时出现错误。
The culprit might be in this useEffect
according to react.罪魁祸首可能是在这个
useEffect
根据反应。
useEffect(() => {
axiosInstance.get('all/buckets/').then((res) => {
const allBuckets = res.data;
setAppState({ loading: false, buckets: allBuckets });
console.log(res.data);
});
}, [setAppState]);
Here the complete component:这里是完整的组件:
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>
);
}
The error is also very inconsistent, it sometimes appears and sometimes it does not, based on the user requesting the data.该错误也非常不一致,根据用户请求数据,有时出现有时不出现。 It could be a backend issue, but currently trying to see if I can tidy up my useEffect better to fix this issue.
这可能是后端问题,但目前正在尝试查看是否可以更好地整理我的 useEffect 以解决此问题。
Thank you for any help.感谢您的任何帮助。
Consider not passing setAppState
as a dependency to your useEffect
hook.考虑不要将
setAppState
作为依赖项传递给您的useEffect
挂钩。
Just use an empty array, so that it only runs once when your GetUserBuckets
component is mounted.只需使用一个空数组,这样它只会在您的
GetUserBuckets
组件安装时运行一次。
Refactor your useEffect to look like this重构你的 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.