【问题标题】:Remembering state in react through refreshes通过刷新在反应中记住状态
【发布时间】:2019-08-23 09:27:06
【问题描述】:

我正在寻找一种在刷新浏览器时将state 存储在本地的解决方案。

我们的应用有许多带有语言选择器的翻译,但目前在浏览器刷新时,此状态会重置为默认值。

在应用程序中,根据授权,我们将选择的语言保存到 Firebase,onMount 会显示选择的用户语言,但是,在我们未经身份验证的页面上,例如登录页面和创建页面,这是不可能的。

目前,使用Context as 选择语言并将其存储为状态

import React, { useReducer } from 'react';

// Translations
import EN from '../../../constants/translations/en.json';
import TR from '../../../constants/translations/tr.json';
import ES from '../../../constants/translations/es.json';

interface InterfaceState {
  langCode?: string;
  translate?: any;
  dispatch: any;
}

const translations: any = {
  en: EN,
  tr: TR,
  es: ES
};

const getTranslate = (langCode: string) => (key: string | number) =>
  translations[langCode][key] || key;

const initialState = {
  langCode: 'en',
  translate: getTranslate('en'),
  dispatch: ''
};

export const I18nContext = React.createContext<InterfaceState>(initialState);

export const I18nContextProvider = ({ children }: any) => {
  const reducer = (state: any, action: { type: any; payload: any }) => {
    switch (action.type) {
      case 'setLanguage':
        return {
          langCode: action.payload,
          translate: getTranslate(action.payload)
        };
      default:
        return { ...initialState };
    }
  };

  const [state, dispatch] = useReducer(reducer, initialState);
  const value = { ...state, dispatch };

  return <I18nContext.Provider value={value as any}>{children}</I18nContext.Provider>;
};

语言选择器使用useContext 设置状态,这在用户刷新浏览器并应用默认langCode 之前工作正常。

我尝试过的一个解决方案有效,但需要大量维护,特别是因为它需要我向Link 组件添加额外的步骤,即添加到history.push(pathname) 并使用langCode 添加一个字符串查询一个字符串作为

const onLanguageSelect = (data: any) => {
  dispatch({ type: 'setLanguage', payload: data.value });
  history.push(location.pathname + `?lang=` + data.value);
};

我的问题,如何将所选状态存储到 sessionlocal 存储?这是一个可行且可扩展的解决方案吗,尤其是跨多个域(如 app.example.com 和 example.com)?

【问题讨论】:

  • 也许你应该把你的状态放到localStorage
  • 我已经调查过了,但没有找到在多个域中使用 localStorage 的方法。
  • multiple domains 是什么意思?
  • app.example.com 和 example.com
  • Cookie 怎么样?

标签: javascript reactjs


【解决方案1】:

您可以使用iframe分享您在localStorage/sessionStorage中保存的内容

这里是link

【讨论】:

    【解决方案2】:

    好问题。我认为本地或会话不是选项。因为它没有跨不同的子域保存。我认为一个选项可能是使用 cookie。 Cookie 可以毫无问题地与多个子域共享。

    选择语言后,只需将其保存在 cookie 中,如果已定义,则在上下文的默认值中获取。

    唯一的缺点是有些人默认关闭了他们的 cookie。因此,您可能需要添加一个提示,建议用户为您的应用程序打开 cookie。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多