如何在Hooks状态更改时强制重新加载页面?

时间:2019-09-02 04:56:17

标签: reactjs react-hooks

我正在使用react挂钩,并且需要在状态更改时刷新页面。

我尝试使用window.location.reload(),但这不会导致正确的刷新。

const responseGoogle = async googleData => {
    await userLogin(googleData);
    setLoggedIn(true);
    window.location.reload()
  };

只有手动F5刷新才能完成!

React中有什么需要完全刷新的东西吗?

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

如果您只是想重新渲染页面,则可以使用挂钩函数,

 .no-click {
   pointer-events:none; //This makes it not clickable
 }


<ion-item class="no-click">
    <ion-avatar slot="start">
        <img [src]="img">
        </ion-avatar>
     <ion-label>{{name}}</ion-label>
  </ion-item>

当您要重新渲染时,只需调用reload函数

print("Product is".product)

只记得从react导入useState;

答案 1 :(得分:0)

即使等待承诺失败,也许您正在运行window.location.reload()。我建议在异步函数中使用trycatch来轻松确定它是否成功。

您可以在下面尝试此代码

const responseGoogle = async googleData => {
  try {
    await userLogin(googleData);
    setLoggedIn(true);
    window.location.reload() //this will run if the await userLogin is succeeded
  } catch (error) { 
   console.log(error); //will show an error if it fails
  }
};

答案 2 :(得分:0)

实际上,我要做的就是向函数window.location.reload(true)中传递布尔值以强制重新加载。