简体   繁体   English

如何在没有 Redux 的情况下在本地存储 React 中持久化状态?

[英]How do I persist state in local storage React without Redux?

I'm building a web app in React connected to Firebase, which authenticates users and stores post data.我正在 React 中构建一个连接到 Firebase 的网络应用程序,它对用户进行身份验证并存储发布数据。 There seems to be a lot of documentation online about using Redux, but not a whole lot on persisting state without it.网上似乎有很多关于使用 Redux 的文档,但关于没有它的持久状态的文档并不多。

When a user refreshes a page, the <App /> 's State is reset, so I need to preserve the existing state/retrieve it from Firebase.当用户刷新页面时, <App />的状态被重置,因此我需要保留现有状态/从 Firebase 检索它。 Some articles suggest using local storage to store state.一些文章建议使用本地存储来存储状态。 But with best practices in mind, what should be stored in local storage?但是考虑到最佳实践,本地存储中应该存储什么? My app stores all it's state in <App /> , and passes down needed state as props to relevant components.我的应用程序将其所有状态存储在<App /> ,并将所需状态作为道具传递给相关组件。

The following two examples assume a user has authenticated already and has just refreshed their page.以下两个示例假设用户已经通过身份验证并且刚刚刷新了他们的页面。 We want their session to be preserved, so do we:我们希望保留他们的会话,所以我们:

Example #1:示例#1:

  • App loads and checks local storage for a stringified object of the last stored local state.应用程序加载并检查本地存储以获取最后存储的本地状态的字符串化对象。 Sets the state to either that or empty state.将状态设置为该状态或空状态。
  • If 'state' is retrieved and set, use this.state['uid'] to sync state with Firebase (fetching), then update local storage state again.如果检索并设置了'state' ,请使用this.state['uid']与 Firebase 同步状态(获取),然后再次更新本地存储状态。
  • Whenever a user updates something, update the state (which updates Firebase) and also update the local storage state.每当用户更新某些内容时,更新状态(更新 Firebase)并更新本地存储状态。
  • When user logs out, clear the local storage 'state' item.当用户注销时,清除本地存储'state'项。

Example #2:示例#2:

  • App loads and checks local storage for a uid (which is set during authentication), if one is found, uses that to sync state with firebase (fetch).应用程序加载并检查本地存储的 uid(在身份验证期间设置),如果找到,则使用它与 firebase 同步状态(获取)。
  • If a user reloads a page, data is fetched again from Firebase.如果用户重新加载页面,则会再次从 Firebase 获取数据。
  • When user logs out, clear the local storage 'uid' item.当用户注销时,清除本地存储'uid'项。

With the first example, I'm effectively keeping two copies of the state.对于第一个示例,我有效地保留了状态的两个副本。 One in React's State , and another in the browser's Local Storage.一个在 React 的State ,另一个在浏览器的 Local Storage 中。 In case the user closes the window or refreshes the page.如果用户关闭窗口或刷新页面。

My question is: Which is the best practice?我的问题是:哪个是最佳实践?

or, is building a React app that needs to persist user and state across different routes without Redux totally bonkers?或者,是否正在构建一个 React 应用程序,它需要在没有 Redux 的情况下在不同的路由上持久化用户和状态?

Learning React is enough of a curve without Redux, so I'm trying to see if I can manage without it.没有 Redux 学习 React 就足够了,所以我想看看我是否可以在没有它的情况下进行。

In your use case, redux is not gonna help you because redux's state also resets when user refreshes the page. 在您的用例中,redux不会帮助您,因为当用户刷新页面时,redux的状态也会重置。 If you want to keep the state of your app on refresh/browser termination, then you need to use localStorage/sessionStorage/cookies etc. 如果您想在刷新/浏览器终止时保持应用程序的状态,那么您需要使用localStorage / sessionStorage / cookies等。

Which is best way? 哪种方式最好?

Well I would say that the second approach is better. 好吧,我会说第二种方法更好。 I would avoid keeping copy of state in localstorage. 我会避免在本地存储中保留州的副本。 I would only keep some kind of token/id (in your case uid ) which uniquely identify the user and would fetch fresh data every time. 我只保留某种令牌/ id(在你的情况下为uid ),它唯一地标识用户并且每次都会获取新数据。 When your application grows it can be hard to manage those states in localstorage. 当您的应用程序增长时,很难在localstorage中管理这些状态。

I`m using the library Master-hook and its quite simple to use global state without Redux:我正在使用库Master-hook并且在没有 Redux 的情况下使用全局状态非常简单:

Then you create 'src/hooks.js' file:然后创建“src/hooks.js”文件:

import MasterHook from 'master-hook'

export const useMyHook = MasterHook({
  storage: "myStorage",
  initialState: {
    myName: 'Vanda',
  },
  cache: {
    myName: 10000,
  }
})

You set the initial State (initialState:...) Set how long the value need has to stay cached in ms (cache:...).您设置初始状态 (initialState:...) 设置值需要以毫秒为单位保持缓存的时间(缓存:...)。 The timer starts when you put a value in initialState and its lifetime in the value in ms.当您将一个值放入 initialState 并将其生命周期放入以毫秒为单位的值中时,计时器就会启动。 Even when you reload your page - the value will save in a Global state and you don`t have to use Redux, react-redux, redux-thunk, reselect are already installed in the library Master-hook.即使你重新加载你的页面 - 该值也会以全局状态保存并且你不必使用 Redux,react-redux、redux-thunk、reselect 已经安装在库 Master-hook 中。

The more information on how to use Master-hook you can find here您可以在此处找到有关如何使用 Master-hook 的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 redux state 与本地存储保持一致 - How do I persist my redux state with local storage 您如何通过反应和本地存储将数据保存在 state 中? - How do you persist data in state with react and local storage? redux-persist:如何在浏览器的本地存储中保存状态? - redux-persist: How to save state on browser's local storage? 如何在 React Native 中进行预取并将数据持久化到本地存储而不阻塞 UI? - How to do prefetch in React Native and persist data to local storage without blocking the UI? 调用更新本地存储的操作(没有 API 调用) - redux 持久化,反应原生 - Calling an action to update local storage (without API call) - redux persist, react native 没有localStorage的情况下如何保留令牌信息? React + Redux - How can i persist token info without localStorage? React + Redux 如何在同一反应组件中使用本地状态以及redux存储状态? - How do I use local state along with redux store state in the same react component? React - 使用 react-numeric-input 将 state 持久保存在本地存储中 - React - persist state in local storage using react-numeric-input React w/ Redux/React-Redux 和 Redux-Persist 仅将第一次更改持久化到本地存储 - React w/ Redux/React-Redux and Redux-Persist only persisting first change to local storage 我怎样才能坚持 redux 状态 - How can I persist redux state
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM