简体   繁体   English

如何存储 redux state

[英]how to store redux state

I am beginner using Redux,I want to store redux's state in my app, because whenever I refresh the page redux will reset the state. this is my the userSlice.js:我是使用 Redux 的初学者,我想在我的应用程序中存储 redux 的 state,因为每当我刷新页面 redux 都会重置 state。这是我的 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商店.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注册.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
            }))
        })

    }

So how exactly can i store the state of the user whenever i refresh the page?那么,每当我刷新页面时,我究竟如何存储用户的 state 呢?

There are some ways.有一些方法。 One that comes to my mind is using localStorage .我想到的是使用localStorage That way you can do something like:这样你就可以做类似的事情:

userSlice.js: userSlice.js:

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

And then it would be initialized if the previous state was saved.然后如果之前的state被保存,它就会被初始化。 All you would need to do is update your localStorage state whenever you update your redux state.您需要做的就是在更新 redux state 时更新 localStorage state。

localStorage.setItem('previousState', newReduxState);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM