问题
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
回答1:
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>
);
}
来源:https://stackoverflow.com/questions/64999492/how-to-store-and-retrieve-objects-in-react-redux-objects-subscribed-to-local-s