【发布时间】:2021-02-22 12:11:38
【问题描述】:
我想在状态改变时重新加载我的页面。现在我正在使用下面的代码,但不知道为什么即使状态没有改变它也会不断地重新加载。
useEffect(() => {
window.location.reload();
}, [state]);
【问题讨论】:
-
这是一个不好的做法,你想完成什么?
我想在状态改变时重新加载我的页面。现在我正在使用下面的代码,但不知道为什么即使状态没有改变它也会不断地重新加载。
useEffect(() => {
window.location.reload();
}, [state]);
【问题讨论】:
useEffect 将始终在第一次渲染后执行,在您的情况下,即使 state 没有更改,它也会在第一次渲染时重新加载页面。我认为您应该在useEffect 中添加类似这样的检查
function YourComponent(){
const initialState = "initial state";
const [state, changeState] = useState(initialState);
useEffect(()=>{
// on first render, state will be initial state, so it will
// not reload, but on subsequent state change, it will reload the page
if(state!==initialState){
window.location.reload()
}
}, [state]);
}
【讨论】: