setShowModal 不起作用 重新渲染太多。 React 限制渲染次数以防止无限循环

时间:2021-07-07 03:54:07

标签: reactjs react-hooks

我想在倒数计时器完成后显示一个模态对话框。我在 if seconds === 0 的条件下调用状态函数,但我不断收到此错误“重新渲染太多。React 限制渲染次数以防止无限循环。”我做错了哪一部分?

let [showModal, setShowModalDialog] = useState(false)
let countRef1 = useRef()
useEffect(() => { getPushNoti() }, [])

const getPushNoti = async () => {
        let sendNoti = 1

         <some code implementation>
         
        if (sendNoti === 1) {
            countRef1.current = setInterval(() => {
                if (secondsPush > 0) {
                    setSecondsPush((prevTimer) => prevTimer - 1)
                }

            }, 1000)
        }
    }

if (secondsPush === 0) {
        clearInterval(countRef1.current)
        setShowModalDialog(true)
    }
    
    {showModal ? (
             <Modal> is here           
 ) : null}

1 个答案:

答案 0 :(得分:1)

我认为您需要在 (secondsPush === 0) 钩子内检查此条件 useEffect 并添加 secondsPush 作为 hook 的依赖项,以便 useEffect 钩子每次 secondsPush 的值改变时都会运行:

let [showModal, setShowModalDialog] = useState(false)
let countRef1 = useRef()
useEffect(() => { getPushNoti() }, [])

const getPushNoti = async () => {
    let sendNoti = 1

     <some code implementation>
     
    if (sendNoti === 1) {
        countRef1.current = setInterval(() => {
            if (secondsPush > 0) {
                setSecondsPush((prevTimer) => prevTimer - 1)
            }

        }, 1000)
    }
}


useEffect(() => { 
  if (secondsPush === 0) {
    clearInterval(countRef1.current)
    setShowModalDialog(true)
  }
}, [secondsPush])

{showModal ? (
         <Modal> is here           
) : null}