简体   繁体   English

如何将我的初始状态放入我的 redux 商店?

[英]How can I put my initial state into my redux store?

I am trying to make a login functionality with redux.我正在尝试使用 redux 制作登录功能。 The problem is I can not figure out how to work with my initial state where I stored my userInfo.问题是我无法弄清楚如何使用我存储用户信息的初始状态。

import { configureStore } from '@reduxjs/toolkit'
import { postListReducer, postDetailsReducer } from './reducers/postReducers'
import { userLoginReducer } from './reducers/userReducers'

const store = configureStore({
  reducer: {
    postList : postListReducer,
    postDetails : postDetailsReducer,
    userLogin : userLoginReducer,
  },
})

const userInfoFromStorage = localStorage.getItem('userInfo') ?
  JSON.parse(localStorage.getItem('userInfo')) : null

const initialState = {
    userLogin : {userInfo: userInfoFromStorage}
  }
  

export default store

I can see that you are using redux toolkit, you might add initial state in userLoginReducer file, there is a prop there for you.我可以看到您正在使用 redux 工具包,您可以在 userLoginReducer 文件中添加初始状态,那里有一个道具适合您。 As for the overral solution i would suggest you to take a look at this repo: https://github.com/rt2zz/redux-persist至于总体解决方案,我建议你看看这个 repo: https ://github.com/rt2zz/redux-persist

Maybe this library is what you are looking for.也许这个库就是你要找的。

Source: https://redux-toolkit.js.org/api/createslice#initialstate来源: https ://redux-toolkit.js.org/api/createslice#initialstate

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

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