[英]How to fix error Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop using react?
i am getting uncaught error.我收到未捕获的错误。 too many re-renders.
太多的重新渲染。
what i am trying to do?我想做什么?
when a button is clicked start function is called and modal popup opens.单击按钮时,将调用启动 function 并打开模式弹出窗口。 once the start function is finished i have to close the modal popup.
一旦启动 function 完成,我必须关闭模式弹出窗口。
below is the code,下面是代码,
enum CheckStatus {
INITIAL,
STARTING,
STARTED,
FINISHED,
FAILED,
}
const useSomeHook = (id) => {
const [status, setStatus] = React.useState(CheckStatus.INITIAL);
const start = React.useCallback(async () => {
setStatus(CheckStatus.STARTING);
let data= undefined;
try {
const { data: checkData } = await startCheck({
variables: { id },
});
data = checkData;
}
//some logic
React.useEffect(() => {
if (status === CheckStatus.STARTED ) {
stopPolling && stopPolling();
setStatus(Check Status.FINISHED);
//once status is finished then i have to close modal popup
}
}
return {
start,
status,
};
};
const Main = () => {
const [openModal,setOpenModal] = React.useState(false);
const {start,status} = useSomeHook(id);
return (
{openModal && (<Modal />)}
);
}
Now i want to set the openModal state to false when status is finished.现在我想在状态完成时将 openModal state 设置为 false。 so i do like below,
所以我喜欢下面,
const Main = () => {
const [openModal,setOpenModal] = React.useState(false);
const {start,status} = useSomeHook(id);
if (status === CheckStatus.FINISHED) {
setOpenModal(false);
} //this gives error
return (
{openModal && (<Modal />)}
);
}
but gives this error但给出了这个错误
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
how can i fix this?我怎样才能解决这个问题? is this right solution?
这是正确的解决方案吗?
also is there a way to set the setOpenModal inside the useSomeHook as soon as status is set to FINISHED?一旦状态设置为 FINISHED,有没有办法在 useSomeHook 中设置 setOpenModal?
could someone help me fix this.有人可以帮我解决这个问题。 thanks.
谢谢。
I'm not 100% sure, but I believe your issues is that you are setting a state every render, which in turn will always re-render, and re-set the state.我不是 100% 确定,但我相信您的问题是您在每次渲染时都设置了 state,而这又将始终重新渲染,并重新设置 state。 The infinite loop.
无限循环。 To work around this you should probably use
useEffect
要解决此问题,您可能应该使用
useEffect
const Main = () => {
const [openModal,setOpenModal] = React.useState(false);
const {start,status} = useSomeHook(id);
React.useEffect(() => {
if (status === CheckStatus.FINISHED) {
setOpenModal(false);
}
}, [status]);
return (
{openModal && (<Modal />)}
);
}
which would only preform the if check whenever status
is changed, instead of on every render.这只会在
status
更改时执行 if 检查,而不是在每次渲染时执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.