从另一个Redux切片中获取值作为不同切片中的初始状态

vybvopom  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(130)

我的应用程序中有两个Redux切片:userSlice和cartSlice。我想从userSlice中获取一个特定的值(userName),并将其分配为cartSlice中属性(user)的初始值。然而,我在实现这一点上遇到了麻烦。
下面是userSlice.js的代码:

import { createSlice } from '@reduxjs/toolkit'

const userNameLocalStorage =
    localStorage.getItem("userRedux") === null
        ? null
        : JSON.parse(localStorage.getItem("userRedux"));

const initialState = {
    userName: userNameLocalStorage,
}

export const userSlice = createSlice({
    name: 'users',
    initialState,
    reducers: {
        updateUser: (state, action) => {
            localStorage.setItem("userRedux", action.payload)
            state.userName = action.payload;
        },
        logOut: (state) => {
            window.localStorage.removeItem('userRedux');
            state.userName = null;
        },

    },
})

export const { updateUser,logOut } = userSlice.actions

export default userSlice.reducer;

下面是cartSlice.js的代码

import { createSlice } from '@reduxjs/toolkit'
import { userSlice } from './userSlice';

const initialState = {
    numberOfItems: 0,
    details: [],
    total: 0,
    user: userSlice?.initialState?.userName,
}
const cartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: {
    },

})

export default cartSlice.reducer;

两者都在同一目录中
我尝试导入userSlice并访问userSlice.initialState.userName作为cartSlice中user属性的初始值,但它没有按预期工作。cartSlice中的user属性始终未定义。
如何从userSlice获取userName值并将其作为cartSlice中user属性的初始值?我错过了什么吗?

dsf9zpds

dsf9zpds1#

参见createSlice()函数的返回值。
createSlice将返回一个类似于:

{
    name : string,
    reducer : ReducerFunction,
    actions : Record<string, ActionCreator>,
    caseReducers: Record<string, CaseReducer>.
    getInitialState: () => State
}

因此,尝试userSlice.getInitialState().userName
软件包版本:

"@reduxjs/toolkit": "^1.9.5",

相关问题