刷新后State和localStorage数据不同
所以我对状态和本地存储有疑问。确切地说,每当我将对象嵌套在themes.dark和themes.light中时,动态代码块中的结果在刷新后会有所不同,即使localStorage数据实际上是正确的。
import { useState, useEffect } from "react";
import store from "store2";
import "./styles.css";
const themes = {
dark: {
theme: "dark"
},
light: {
theme: "light"
}
};
export default function App() {
const defaultDarkTheme = window.matchMedia("(prefers-color-scheme:dark)")
.matches
? themes.dark
: themes.light;
const [theme, setTheme] = useState(store.get("theme") || defaultDarkTheme);
useEffect(() => {
store.set("theme", theme);
}, [theme]);
return (
<>
<div
className="App"
onClick={() =>
theme === themes.dark ? setTheme(themes.light) : setTheme(themes.dark)
}
>
{JSON.stringify(theme)}
</div>
{theme === themes.dark
? JSON.stringify(themes.dark)
: JSON.stringify(themes.light)}
</>
);
}
刷新前:
刷新后:
这是一个很大的问题,因为刷新后而不是生成黑暗模式的内容生成轻量级的内容。
So I have a problem with state and localStorage. To be exact, whenever I nest the objects inside of the themes.dark and themes.light the results in dynamic codeblock differ after refresh even though the localStorage data is in fact correct.
import { useState, useEffect } from "react";
import store from "store2";
import "./styles.css";
const themes = {
dark: {
theme: "dark"
},
light: {
theme: "light"
}
};
export default function App() {
const defaultDarkTheme = window.matchMedia("(prefers-color-scheme:dark)")
.matches
? themes.dark
: themes.light;
const [theme, setTheme] = useState(store.get("theme") || defaultDarkTheme);
useEffect(() => {
store.set("theme", theme);
}, [theme]);
return (
<>
<div
className="App"
onClick={() =>
theme === themes.dark ? setTheme(themes.light) : setTheme(themes.dark)
}
>
{JSON.stringify(theme)}
</div>
{theme === themes.dark
? JSON.stringify(themes.dark)
: JSON.stringify(themes.light)}
</>
);
}
Before refresh :
After refresh :
It's pretty problematic since after refresh instead of generating the content for dark mode it generates the content for the light one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
您的问题不在于状态或存储。如果您在声明状态后添加以下行并在将其更改为黑暗后刷新页面,您将看到您的问题。console.log(theme, theme.dark, theme === theme.dark)
Javascript 仅在两个对象引用完全相同的对象时才判定它们相等。但是,当您从商店获取主题对象时,它与您之前定义的 theme.dark 对象并不完全相同。
有多种方法可以处理这样的场景,但我认为如果您比较对象的某些字符串属性,这将是最简单的,例如,
theme.theme === themes.dark.theme
? JSON.stringify(themes.dark)
: JSON.stringify(themes.light)
或者您可以在主题对象上定义一个唯一标识符属性,您可以用它来比较theme.theme
或者如果你真的想比较对象,你可以这样做
JSON.stringify(theme) === JSON.stringify(themes.dark)
? JSON.stringify(themes.dark)
: JSON.stringify(themes.light)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我认为这是因为你的
useEffect
钩子。我认为您的
useEffect
在从 localStorage 获取数据之前运行。我不确定这只是一种预感。I think it is because of your
useEffect
hook.I think your
useEffect
runs before it gets the data from the localStorage. I'm not sure this is just a hunch.