reactjs - 如何处理本地存储和 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一无所知,所以我有点迷茫,不知道如何编码。有人可以帮忙吗?
解决方案
我相信您的代码已正确设置为 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
按下按钮或更改主题来通过。
这个关于强制重新渲染的问题可能会对您有所帮助。
推荐阅读
- spring - 如何在春季停止shell命令注入
- node.js - 使用节点 js 进行 Firebase 谷歌身份验证
- mysql - 如何附加 pg_dump 备份命令 PostgreSQL 的日志输出
- excel - 在 Excel 中提取以 B 开头且长度为 10 个字符的单词
- java - 如何在春季回滚整个循环的事务?
- python-3.x - 我想了解如何在 holoviews 1.12.7 版本中实现此代码。我在折旧版本中完成了
- c# - 问题将 .IsSelected 复选框计数绑定到 Label WPF
- swift - 将 NULL 值添加到 httpBody Post 请求 - REST API - Swift
- anylogic - 如何检测无限循环?
- android - Android中的文件是如何被覆盖的?