简体   繁体   English

处理Redux中的长寿状态

[英]Handling long lived state in Redux

I am building an application that requires a user to be a certain age before entering the site. 我正在构建一个应用程序,要求用户在进入网站之前达到一定年龄。 The user is shown a form in which they must enter their date of birth, this information is then saved to local storage and then on every request check if that value is set in local storage. 向用户显示他们必须输入出生日期的表格,然后将该信息保存到本地存储,然后在每次请求时检查该值是否在本地存储中设置。 Currently inside main.js the checking code looks like: 目前在main.js ,检查代码如下所示:

let hasRememberedAge = localStorage.getItem('ageVerified')
if (hasRememberedAge !== null) {
  store.dispatch(ageVerified())
}

This feels wrong, my question what is a better way to handle this? 这感觉不对,我的问题是什么是更好的方法来处理这个? Should I fire an action on every page load which then triggers these checks? 我应该在每个页面加载时触发一个动作然后触发这些检查吗? If so where should this dispatch live? 如果是这样,这次dispatch应该在哪里?

I don't see anything wrong with this. 我没有看到任何错误。 You can do this wherever you create the store. 您可以在创建商店的任何地方执行此操作。

Alternatively you can serialize a part of your state in a store.subscribe callback, and read it from the localStorage before creating the store. 或者,您可以在store.subscribe回调中序列化您的州的一部分,并在创建商店之前从localStorage读取它。 You can pass such persisted state as a second argument to createStore to preload it. 您可以将此持久状态作为第二个参数传递给createStore以预加载它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM