如何在 react-redux 中存储和检索对象?[订阅本地存储的对象] [英] How to store and retrieve objects in react-redux? [Objects subscribed to local-storage]
问题描述
我有一个这样的减速器:
const UserReducer = (state=JSON.parse(localStorage.getItem('user')), action) =>{开关(动作.类型){默认:返回状态;案例REFRESH_AUTH":返回状态 = JSON.parse(JSON.stringify(action.payload.user));案例CLEAR_AUTH":返回状态 = 空;}}
我需要在这里存储一个对象,因此我需要在保存之前对其进行字符串化.但是,现在,当我重新加载页面并且减速器尝试获取
JSON.parse(localStorage.getItem('user'))
我收到此错误:
Uncaught SyntaxError: Unexpected token o in JSON at position 1在 JSON.parse (<匿名>)在用户 (authReducers.js:7)在 redux.js:367在 Array.forEach (<匿名>)在 redux.js:365在 s (redux.js:430)在 Module.79 (index.js:5)在 ((索引):1)在 t ((索引):1)在 Array.r [as push] ((index):1)
我该如何解决这个问题,还有,使用 redux 存储和检索对象的正确方法是什么?
基本上,这就是我想要做的:将用户对象作为 JSON.stringified 版本存储到 localStorage 中,然后通过 reducer [JSON.parse] 访问它
好吧,那么,存储对象并备份它们 [订阅它们] localStorage 的解决方案就是这样.
我从状态中存储并返回对象的字符串化版本.然后当我想重新获取它时,就像在 react- 组件中一样,我只是 JSON.parse 它.
它避免了你必须经历的所有麻烦,而且似乎是唯一的方法,因为 redux 和 localStorage 实际上不能存储对象,只能存储字符串.
代码如下:
const UserReducer = (state=localStorage.getItem('user'), action) =>{开关(动作.类型){默认:返回状态;案例REFRESH_AUTH":返回状态 = JSON.stringify(action.payload.user);案例CLEAR_AUTH":返回状态 = 空;}}
检索对象状态变量:
函数用户区域(){const user = JSON.parse(useSelector(state => state.user));const full_name = user.first_name + ' ' + user.last_name;函数注销用户(){axios.post('/api/logout/').then(() => {<重定向到='/login/'/>}).catch(error => {console.log(error)});}返回 (<div className="user-area"><div className="button-container"><按钮><SettingsIcon fontSize="继承"/>按钮><button onClick={logoutUser}><ExitToAppIcon fontSize=继承"/>按钮>
<div className="user-container"><div><h2>{truncate(user.username, 13)}</h2><h3>{truncate(full_name, 15)}</h3>
<img src={user.avatar_url} className={user.has_premium ?高级头像图标":"defaultAvatarIcon>}</img>