如何添加本地存储以在 Gatsby 中保留暗模式主题
How to add local storage to persist dark mode theme in Gatsby
我已经尝试了所有方法来添加本地存储以保留主题。关于如何使用现有代码实施的任何想法?我在第一次渲染时混合了相互矛盾的主题。我尝试在设置主题时实现本地存储。
const setTheme = type => {
localStorage.setItem("theme", setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}
const initState = {
theme: localStorage.getItem("theme"),
setTheme: setTheme,
}
const [state, setState] = useState(initState)
ThemeProvider.js
export const ThemeContext = React.createContext({
theme: {
},
setTheme: () => {},
})
export const ThemeContextProvider = props => {
const theme = {
light: {
},
dark: {
},
}
const setTheme = type => {
setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}
const initState = {
theme: theme.light,
setTheme: setTheme,
}
const [state, setState] = useState(initState)
return (
<ThemeContext.Provider value={state}>
{props.children}
</ThemeContext.Provider>
)
}
这一行对我来说没有意义:
const setTheme = type => {
localStorage.setItem("theme", setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}
您想在 localstorage 中设置一个项目,但却在 setItem 函数中设置 React 状态?
需要注意两点:
- 不要在 localStorage.setItem 函数中设置 React 状态
- 您只能在 localStorage 中保存字符串化值。如果不将 JavaScript 对象转换为 json 字符串,则无法保存它。
这是正确的:
const setTheme = type => {
localStorage.setItem("theme", state.theme }); // only save the theme value "dark" or "light" as a string
}
您需要根据localStorage或initialState中的值触发设置状态。为此使用 useffect
。 告诉你怎么做。
我已经尝试了所有方法来添加本地存储以保留主题。关于如何使用现有代码实施的任何想法?我在第一次渲染时混合了相互矛盾的主题。我尝试在设置主题时实现本地存储。
const setTheme = type => {
localStorage.setItem("theme", setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}
const initState = {
theme: localStorage.getItem("theme"),
setTheme: setTheme,
}
const [state, setState] = useState(initState)
ThemeProvider.js
export const ThemeContext = React.createContext({
theme: {
},
setTheme: () => {},
})
export const ThemeContextProvider = props => {
const theme = {
light: {
},
dark: {
},
}
const setTheme = type => {
setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}
const initState = {
theme: theme.light,
setTheme: setTheme,
}
const [state, setState] = useState(initState)
return (
<ThemeContext.Provider value={state}>
{props.children}
</ThemeContext.Provider>
)
}
这一行对我来说没有意义:
const setTheme = type => {
localStorage.setItem("theme", setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}
您想在 localstorage 中设置一个项目,但却在 setItem 函数中设置 React 状态?
需要注意两点:
- 不要在 localStorage.setItem 函数中设置 React 状态
- 您只能在 localStorage 中保存字符串化值。如果不将 JavaScript 对象转换为 json 字符串,则无法保存它。
这是正确的:
const setTheme = type => {
localStorage.setItem("theme", state.theme }); // only save the theme value "dark" or "light" as a string
}
您需要根据localStorage或initialState中的值触发设置状态。为此使用 useffect
。