状态存储在localStorage得到覆盖在页面刷新在React redux?如何持久化状态?



我正在向用户数组添加用户对象,就像这样,用户:[{},{},.....]。最终,这个用户列表被呈现给UI。到目前为止一切正常,但是每次刷新页面并想要向users数组添加一个新的user-object时,它都会覆盖现有的数组并清除UI。当然,我希望数据能够持久保存并在UI中保持可见。
我想用react-redux在localStorage中持久化状态来实现这一点。下面的代码显示了我到目前为止所做的工作。

// Store
const reducer = combineReducers({
cats: getCatReducer,
users: registerReducer,
})
const persistedState = loadState();
const initialState = {
cats: {cat: []},
users: {users:[]},
persistedState,
}
const store = configureStore(
{
reducer,
initialState,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(thunk),
})
store.subscribe(() => {
saveState(store.getState());
});
export default store

//LocalStorage
export const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
export const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (error) {
// ignore write errors
console.log(error.message)
}
};


//Action
export const register = (user) => (dispatch) => {
dispatch({ type: REGISTER_SUCCESS, payload: user })
}

//Reducer
export const registerReducer = (state = { users: [] }, action) => {
switch (action.type) {
case REGISTER_REQUEST:
return { loading: true };
case REGISTER_SUCCESS:
let user = action.payload
return { ...state, users: [...state.users, user], loading: false };
case REGISTER_FAIL:
return { loading: false, error: action.payload };
default:
return state;
}
}
//screen component
const UserScreen = () => {
const users = useSelector(state => state.users.users)
return (
<>
{users.map((user, index) => {
return (
<div key={user.id} className={styles.userInfo}>
<div className={styles.user}> {user.name}</div>
<div className={styles.user}>{user.address}</div>
<div className={styles.user}>{user.country}</div>
<div className={styles.user}>{user.email}</div>
</div>
)
})}
</>
)
}
//LocalStorage log
JSON.parse(localStorage.getItem('state')) -->
{users: {...}}
{
"users": [
{
"id": "89526872-8b33-46f4-86a2-faa83ae9686f",
"name": "John Doe",
"email": "john@example.com",
"address": "SandyRoad 456",
"country": "USA",
"password": "123"
},
{
"id": "400a4226-c287-415a-b6af-4d119dc75e79",
"name": "Jane Doe",
"email": "jane@example.com",
"address": "Hill 78",
"country": "USA",
"password": "123"
}
],
"loading": false
}
//Redux DevTools (raw) before refreshing the page!
{
cats: {
cat: []
},
users: {
users: [
{
id: '89526872-8b33-46f4-86a2-faa83ae9686f',
name: 'John Doe',
email: 'john@example.com',
address: 'SandyRoad 456',
country: 'USA',
password: '123'
},
{
id: '400a4226-c287-415a-b6af-4d119dc75e79',
name: 'Jane Doe',
email: 'jane@example.com',
address: 'Hill 78',
country: 'USA',
password: '123'
}
],
loading: false
}
}

似乎您没有正确初始化状态。persistedState将是redux状态下的另一个属性(您应该能够在redux开发工具中看到它)。您可能尝试实现的是覆盖空的catsusers属性。改变

const initialState = {
cats: cat: [],
users: [],
persistedState,
}

const initialState = {
cats: cat: [],
users: [],
...persistedState,
}

最新更新