[英]it have Warning which "Cannot update a component while rendering to a different component" after finished the auto count down function
I created a <Backdrop />
component and called in <App />
我创建了一个
<Backdrop />
组件并调用了<App />
In <App />
, having a button to call out the <Backdrop />
.在
<App />
中,有一个按钮可以调出<Backdrop />
。 Inside of the <Backdrop />
, it has a useEffect
to handle the count down function and render the count.在
<Backdrop />
内部,它有一个useEffect
来处理倒计时 function 并呈现计数。 After the count is down to 0
, the <Backdrop />
will close.计数下降到
0
后, <Backdrop />
将关闭。
In fact, the modal can close when the count is down to 0
, but it will have a warning that Warning: Cannot update a component (`App`) while rendering a different component (`Backdrop`).
事实上,当计数下降到
0
时,模式可以关闭,但它会发出Warning: Cannot update a component (`App`) while rendering a different component (`Backdrop`).
const [modal, setModal] = useState(false);
return{
<View>
<Button onPress={() => setModal(true)}/>
<Backdrop modal={modal} callback={() => setModal(false)}/>
</View>
}
const [count, setCount] = useState(0);
useEffect(() => {
if (modal) {
setCount(3);
const tmp = setInterval(() => {
setCount(prev => {
let newCount = --prev;
if (newCount === 0) {
callback();
clearInterval(tmp);
}
return newCount;
});
}, 1000);
}
}, [modal]);
return{
<Modal>
<Text>{count}</Text>
</Modal>
}
Don't update multiple states inside the useState
updater function. Track the count in another useEffect
, and close the modal when it reaches 0:不要在
useState
更新程序 function 中更新多个状态。在另一个useEffect
中跟踪计数,并在它达到 0 时关闭模式:
const { useState, useEffect } = React; const Parent = () => { const [modal, setModal] = useState(false); return ( <div> <button onClick={() => setModal(true)}>Show modal</button> {modal && <Backdrop onClose={() => setModal(false)} />} </div> ); } const Backdrop = ({ onClose }) => { const [count, setCount] = useState(3); useEffect(() => { const interval = setInterval(() => { setCount(prev => prev - 1); }, 1000); return () => { clearInterval(interval); }; }, []); useEffect(() => { if (count === 0) onClose(); }); return <div>{count}</div>; }; ReactDOM.createRoot(root).render(<Parent />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.