【问题标题】:Wait till page is refreshed: React等到页面刷新:反应
【发布时间】:2021-09-15 01:41:47
【问题描述】:

我有一个 React 组件,它有一个按钮,单击时会打开一个侧窗格。我想先刷新页面,等它完全刷新后再打开侧面板。这是我当前的代码:

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

<button onClick={() => {
    refreshPage(); // Refreshing here and then opening the sidePane
    setIsPaneOpen(true);
}} className="btn-default">Click me</button>
                               

我尝试过睡眠和等待,但这取决于所有因素,对吧?所以它不能被信任。

【问题讨论】:

  • 这不是反应方式。为什么要重新加载页面?你想达到什么目的?设置状态并更新需要更新的东西。

标签: javascript reactjs typescript react-hooks


【解决方案1】:

如果页面被刷新,存储在内存中的所有内容(所有变量、组件状态等)都会丢失。你需要使用localStorage来知道页面加载和组件挂载时是否需要打开侧边栏:

useEffect(() => {
  // This runs when the component is mounted (after the page loads).

  if (localStaorage.getItem('openSidebarOnLoad') === 'true') {
    setIsPaneOpen(true);

    localStorage.removeItem('openSidebarOnLoad');
  }
}, []);

const handleButtonClick = () => {
  localStorage.setItem('openSidebarOnLoad', true);

  window.location.reload();
};

<button onClick={ handleButtonClick } className="btn-default">Click me</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2018-02-15
    • 1970-01-01
    • 2018-09-08
    • 2020-10-31
    • 2018-10-06
    相关资源
    最近更新 更多