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

时间:2020-08-08 23:11:44

标签: reactjs local-storage themes gatsby react-context

我已经尽一切努力添加本地存储以保留主题。关于如何使用现有代码实现的任何想法?第一次渲染时,我会遇到一些相互矛盾的主题。设置主题时,我尝试实现本地存储。

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

1 个答案:

答案 0 :(得分:0)

这行对我来说没有意义:

.AddOpenIdConnect("oidc", options =>
{
    options.Events = new OpenIdConnectEvents 
    {
        OnTicketReceived = context =>
        {
            //Goes through returned claims from authentication endpoint and looks for
            //localization info. If found and different, then new CultureInfo is set.
            string? culture = context.Principal?.FindFirstValue(JwtClaimTypes.Locale);
            if (culture != null && CultureInfo.CurrentUICulture.Name != culture)
            {
                context.HttpContext.Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(
                        new RequestCulture(culture, culture)),
                        new CookieOptions 
                        { Expires = DateTimeOffset.UtcNow.AddYears(1) }
                    );
            }
            return Task.CompletedTask;
        };
    }
});

您想在localstorage中设置一个项目,而是在setItem函数中设置React状态?

注意两点:

  • 不要在localStorage.setItem函数中设置React状态
  • 您只能将字符串化的值保存在localStorage中。您不能保存JavaScript对象,除非将其转换为json字符串。

这是正确的:

const setTheme = type => {
  localStorage.setItem("theme", setState({ ...state, theme: type === "dark" ? theme.light : theme.dark })
}

您需要根据localStorage或initialState中的值触发设置状态。为此使用const setTheme = type => { localStorage.setItem("theme", state.theme }); // only save the theme value "dark" or "light" as a string } answer告诉您如何操作。