如何在 react-redux 中存储和检索对象?[订阅本地存储的对象] [英] How to store and retrieve objects in react-redux? [Objects subscribed to local-storage]

查看:41
本文介绍了如何在 react-redux 中存储和检索对象?[订阅本地存储的对象]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的减速器:

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>

);}

I have a reducer like this:

const UserReducer = (state=JSON.parse(localStorage.getItem('user')), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            return state = JSON.parse(JSON.stringify(action.payload.user));
        case "CLEAR_AUTH":
            return state = null;

    }
}

I need to store an object here, and hence I need to stringify it before saving it. Now, though, when I reload the page and the reducer tries to get

JSON.parse(localStorage.getItem('user'))

I get this error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at user (authReducers.js:7)
    at redux.js:367
    at Array.forEach (<anonymous>)
    at redux.js:365
    at s (redux.js:430)
    at Module.79 (index.js:5)
    at a ((index):1)
    at t ((index):1)
    at Array.r [as push] ((index):1)

how Can I resolve this, and also, what's the correct way to store and retrieve objects with redux?

Basically, here's what I want to do: store the user object as JSON.stringified version to localStorage and then access it through the reducer [JSON.parse] it

解决方案

Alright, so, the solution to storing objects and backing them up [subscribing them to] localStorage was this.

I store and return the stringified version of the object from the state. And then when I want to retieve it, like in a react- component, I just JSON.parse it.

It avoids all the hazzles you have to go through and seems to be the only way, because redux and localStorage cannot actually store objects, just strings.

Here's the code:

const UserReducer = (state=localStorage.getItem('user'), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_AUTH":
            return state = JSON.stringify(action.payload.user);
        case "CLEAR_AUTH":
            return state = null;

    }
}

Retrieving the object state variable:


function UserArea() {
    const user = JSON.parse(useSelector(state => state.user));
    const full_name = user.first_name + ' ' + user.last_name;

    function logoutUser() {
        axios.post('/api/logout/')
            .then(() => {
                <Redirect to='/login/' />
            })
            .catch(error => {console.log(error)});

    }

    return (
        <div className="user-area">
            <div className="button-container">
                <button> <SettingsIcon fontSize="inherit"/> </button>
                <button onClick={logoutUser}>
                <ExitToAppIcon fontSize="inherit"/> </button>
            </div>

            <div className="user-container">
                <div>
                    <h2>{truncate(user.username, 13)}</h2>
                    <h3>{truncate(full_name, 15)}</h3>
                </div>
                <img src={user.avatar_url} className={user.has_premium ? "premiumAvatarIcon" : "defaultAvatarIcon"}></img>
            </div>

        </div>
    );

}

这篇关于如何在 react-redux 中存储和检索对象?[订阅本地存储的对象]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆