【问题标题】:React How to trigger page reload on state changeReact如何在状态更改时触发页面重新加载
【发布时间】:2021-02-22 12:11:38
【问题描述】:

我想在状态改变时重新加载我的页面。现在我正在使用下面的代码,但不知道为什么即使状态没有改变它也会不断地重新加载。

useEffect(() => {
    window.location.reload();
  }, [state]);

【问题讨论】:

  • 这是一个不好的做法,你想完成什么?

标签: html reactjs reload


【解决方案1】:

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]);
}   

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多