Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在Gatsby中添加本地存储以保持暗模式主题_Reactjs_Local Storage_Themes_Gatsby_React Context - Fatal编程技术网

Reactjs 如何在Gatsby中添加本地存储以保持暗模式主题

Reactjs 如何在Gatsby中添加本地存储以保持暗模式主题,reactjs,local-storage,themes,gatsby,react-context,Reactjs,Local Storage,Themes,Gatsby,React Context,我已经尽了一切努力来添加本地存储来持久化主题。关于如何使用现有代码实现有什么想法吗?在第一次渲染时,我混合了一些相互冲突的主题。设置主题时,我尝试实现本地存储 const setTheme = type => { localStorage.setItem("theme", setState({ ...state, theme: type === "dark" ? theme.light : theme.dark }) } const i

我已经尽了一切努力来添加本地存储来持久化主题。关于如何使用现有代码实现有什么想法吗?在第一次渲染时,我混合了一些相互冲突的主题。设置主题时,我尝试实现本地存储

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>
      )
    } 

export const ThemeContext=React.createContext({
主题:{
},
setTheme:()=>{},
})
export const ThemeContextProvider=props=>{
常量主题={
灯光:{
},
黑暗:{
},
}
const setTheme=type=>{
setState({…状态,主题:类型==“暗”?theme.light:theme.dark})
}
常量initState={
主题:theme.light,
setTheme:setTheme,
}
const[state,setState]=useState(initState)
返回(
{props.children}
)
} 

这一行对我来说毫无意义:

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
。这告诉你怎么做