首页 > 解决方案 > 如何处理本地存储和 SSR?

问题描述

<ThemeProvider/>用 React 创建了一个使用 useContext。在开发环境中一切正常。我能够将颜色传递给组件,并localStorage使用 useEffect 挂钩存储选定的颜色主题(可以通过单击按钮来选择主题颜色)。然后可以localStorage在刷新后检索选定的主题颜色。

我设法在 Netlify 上部署了网站,而我在开发环境中为本地存储编写的内容现在的行为方式不同了。我现在无法从本地存储中检索选定的主题颜色。

这是一个代码片段:

const [state, setState] = useState({
       count: 0,
       mainColor: themesArray[getTheme()].mainColor,
       secondColor: themesArray[getTheme()].secondColor,
       thirdColor: themesArray[getTheme()].thirdColor,
       mainFilter: themesArray[getTheme()].mainFilter,
       secondFilter: themesArray[getTheme()].secondFilter,
       boxShadowRGB1: themesArray[getTheme()].boxShadowRGB1,
       boxShadowRGB2: themesArray[getTheme()].boxShadowRGB2,
       boxShadowRGB3: themesArray[getTheme()].boxShadowRGB3
   });

useEffect(() => {
   localStorage.setItem('theme', JSON.stringify(state.count));
}, [state.count]);

function getTheme() {
   if (typeof window === 'object' || typeof window !== 'undefined') {
       const savedTheme = JSON.parse(localStorage.getItem('theme'));
       return savedTheme || 0;
   } else return 0;
}

在 getTheme() 方法中,对于构建过程,我必须包装localStorage一个条件,因为窗口对象在构建期间不可用。我写了 return 0 (用于指向我的主题数组中的第一个主题),因为否则它返回 undefined 并且构建失败。问题是,在生产中,通过以这种方式编写它,我无法在刷新后检索选定的主题。但是在开发工具中,我可以看到我的主题项目存储有很好的价值。我对SSR一无所知,所以我有点迷茫,不知道如何编码。有人可以帮忙吗?

标签: reactjslocal-storagegatsbyserver-side-rendering

解决方案


我相信您的代码已正确设置为 SSR 和 localStorage。这更多是关于使用 React 钩子触发重新渲染的问题。

我认为这就是它不加载您的主题的原因:

useEffect(() => {
  localStorage.setItem('theme', JSON.stringify(state.count));
  // no rerender triggered
}, [state.count]); 

您不会更改 useEffect 中的状态。您需要一些方法来触发重新渲染,以便您可以看到新主题。通过改变状态触发重新渲染:

useEffect(() => {
  localStorage.setItem('theme', JSON.stringify(state.count));
  // React rerenders on state change
  setState({
    ...state,
    count: newCount,
  });
}, [state.count]); 

您可以通过newCount按下按钮或更改主题来通过。

这个关于强制重新渲染的问题可能会对您有所帮助。


推荐阅读