如何存储 redux 状态

how to store redux state

我是 Redux 的初学者,我想在我的应用程序中存储 redux 的状态,因为每当我刷新页面时,redux 都会重置状态。 这是我的 userSlice.js:

import { createSlice } from '@reduxjs/toolkit'
const initialState = {
    userName: null,
    userEmail: null
}

const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        setActiveUser: (state, action) => {
            state.userName = action.payload.userName
            state.userEmail = action.payload.userEmail

        },
        setUserLogOutState: state => {
            state.userName = null
            state.userEmail = null

        }
    }
});

export const { setActiveUser, setUserLogOutState } = userSlice.actions
export const selectUserName = state => state.user.userName
export const selectUserEmail = state => state.user.userEmail

export default userSlice.reducer

store.js

import { configureStore } from '@reduxjs/toolkit'
import userReducer from './userSlice'
export default configureStore({
    reducer: {
        user: userReducer
    }
})

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')

Signup.js

 const dispatch = useDispatch()
    const userName = useSelector(selectUserName)
    const userEmail = useSelector(selectUserEmail)
    const onClickButton = (e) => {
        e.preventDefault();
        signInWithGoogle().then((result) => {
            dispatch(setActiveUser({
                name: result.user.displayName,
                email: result.user.email
            }))
        })

    }

那么我如何在刷新页面时准确地存储用户状态?

有一些方法。我想到的是使用 localStorage。 这样你就可以做类似的事情:

userSlice.js:

const savedState = localStorage.getItem('previousState');
const initialState = savedState ? savedState  : {
  userName: null,
  userEmail: null
}

然后如果之前的状态被保存,它就会被初始化。 您需要做的就是在更新 redux 状态时更新您的 localStorage 状态。

localStorage.setItem('previousState', newReduxState);