【问题标题】:Gatsby Link State is lost when I refresh the page刷新页面时 Gatsby 链接状态丢失
【发布时间】:2020-01-20 09:17:38
【问题描述】:

我正在使用 Gatsby 提供的 Link 组件中的 state 道具发送状态数据。

<Link
  to={`/photos`}
  state={{ photoData }}
>
  View Photo
</Link>

当我单击View Photo 链接时,它会转到photos 页面,我可以从props.location.state 获取photoData。 问题是当我刷新页面时,这个photoData 被清除了。 这在development 模式下运行良好,因此即使在我刷新photos 页面后photoData 仍然存在。 但它在production 模式下不起作用。 我正在考虑将数据存储到 redux 存储,但这太过分了。

有解决这个问题的办法吗?

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

    我遇到了同样的问题,最后我使用了一个将状态保存在本地存储中的钩子。我不知道你是否使用钩子,但假设你是这应该可以解决你的问题:

    import { useEffect, useState } from 'react';
    
    export const usePersistState = (key: string | any, defaultValue: string | boolean | any) => {
      const [value, setValue] = useState(() => {
        if (typeof window !== 'undefined') {
          const persistedState = window.localStorage.getItem(key);
          return persistedState !== null ? JSON.parse(persistedState) : defaultValue;
        }
      });
    
      useEffect(() => {
        window.localStorage.setItem(key, JSON.stringify(value));
      }, [key, value]);
      return [value, setValue];
    };
    

    这会根据 localStorage 项设置您的状态,因此它应该有一个布尔值。然后将其导入到您的组件中,并像 useState 一样使用它。

    import { usePersistState } from 'hooks/use-persist-state';
    
    const [state, setState] = usePersistState('localStorageKey', localStorageValue);
    

    我用它来保存我从 API 调用的数据,并显示/隐藏 cookie 同意横幅,所以它有很多用途。快乐的编码,希望这能解决你的问题!

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。 就我而言,这是因为我每次访问链接时都会打开一个新标签。 解决它的一种可能方法是使用window.history.state(根据这个已解决的问题:https://github.com/gatsbyjs/gatsby/issues/9091)。

      【讨论】:

        【解决方案3】:

        在页面之间的转换过程中设置状态。换句话说,它从一页传递到另一页。当您刷新目标页面时,location.state 将为 null,因为状态应该来自上一页。

        【讨论】:

          【解决方案4】:

          如果刷新页面,将状态放入本地存储状态肯定会丢失

          【讨论】:

            猜你喜欢
            • 2020-08-28
            • 2019-02-09
            • 2018-11-17
            • 1970-01-01
            • 2020-04-30
            • 1970-01-01
            • 1970-01-01
            • 2019-09-12
            • 2018-09-17
            相关资源
            最近更新 更多