首页 > 解决方案 > 如何更新 React Redux 状态

问题描述

我得到了用户的预定义数据,该用户使用代码顶部的 useSelectore 状态登录,但是当我想更改用户配置文件的值时

onSubmit=
    {async values => {
                        await updateUser(values).then((data) => {
                        store.dispatch(setCurrentUser(data));
                        store.subscribe();
                        console.log("store", store.getState().auth.user);//it shows the state has been updated

      });
    }}

它在视图中更改并在数据库中更新,但是当我刷新页面时,它显示来自商店的旧相同值我的减速器

const auth = createSlice({
name: 'auth',
initialState,
reducers: {
    setCurrentUser : (state, action) => {
        state.isAuthenticated = true;
        state.user = action.payload;

    }....})

更新状态的文档让我更加困惑

 function select(state) {
  return state.some.deep.property
 }

let currentValue
function handleChange() {
 let previousValue = currentValue
 currentValue = select(store.getState())

 if (previousValue !== currentValue) {
   console.log(
     'Some deep nested property changed from',
     previousValue,
     'to',
     currentValue
    )
 }
}

 const unsubscribe = store.subscribe(handleChange)
 unsubscribe()

标签: reactjsreact-reduxstoresubscribe

解决方案


Redux 是内存存储。然后你刷新页面它会消失。

所以你必须使用 localStorage 或 indexedDB 来存储你的数据。

查看此类库以更好地理解https://github.com/rt2zz/redux-persist

您需要从 localStorage 获取初始状态,并在每次更改时将您的 redux 状态保存到 localStorage。

const storeKey = 'your-unique-key-name';
function persist() {
    localStorage[storeKey] = JSON.stringify(store.getState);
}
store.subscribe(persist);

...
const initialState = localStorage[storeKey] ? JSON.parse(localStorage[storeKey]) : undefined;

推荐阅读