简体   繁体   English

在 React TypeScript 中异步/等待页面重新加载

[英]Async/Await a Page Reload in React TypeScript

I am having a button, and when I click on it, it should do the following things in order:我有一个按钮,当我点击它时,它应该按顺序执行以下操作:

  • First refresh the Page首先刷新页面
  • Then Open the Side Pane in React然后在 React 中打开侧窗格

This is my code snippet that is existing:这是我现有的代码片段:

<button onClick={() => {
    refreshPage();
    setPaneIsOpen(true);
}}>Click me</button>

const refreshPage = () => {
    window.location.reload();
}

setPaneIsOpen is a State that when set to true, will open the side pane. setPaneIsOpen 是一种状态,当设置为 true 时,将打开侧窗格。 I want to specifially first refresh the page and then set the Pane.我想特别先刷新页面,然后设置窗格。

I have tried this async/await promise approach:我尝试过这种异步/等待承诺方法:

 function refreshPagePromise() {
      return new Promise<void>((resolve) => {
           window.location.reload();
           resolve();
      });
 }

 async function refreshAndOpen() {
      await refreshPagePromise();
      setIsPaneOpen(true);
 }

 <button onClick={() => { refreshAndOpen(); }}>Click me</button>

But I cannot seem to handle page reload.但我似乎无法处理页面重新加载。 I tried to create a Code Sandbox, but since this is very complex, I could not.我试图创建一个代码沙箱,但由于这非常复杂,我不能。 I will try to add one in the edits If I was able to reproduce.如果我能够重现,我会尝试在编辑中添加一个。

One hacky way would be to use localStorage.一种hacky 方法是使用localStorage。

add this useEffect that runs on page load:添加在页面加载时运行的 useEffect:

useEffect(() => {
    const shouldOpenPane = !!localStorage.getItem("setPaneOpen")
    if(shouldOpenPane){
        setIsPaneOpen(true);
        // Maybe the row beneath should not be there, 
        // Idk what behaviour u want if user reloads page manually
        localStorage.removeItem("setPaneOpen")
    }
}, []);

Update your button like this:像这样更新你的按钮:

<button
      onClick={() => {
        localStorage.setItem("setPaneOpen", "true"); // can be set to any thruthy value
        refreshPage();
      }}
    >
      Click me
    </button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM