我的应用程序中有两个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属性的初始值?我错过了什么吗?
1条答案
按热度按时间dsf9zpds1#
参见
createSlice()
函数的返回值。createSlice
将返回一个类似于:因此,尝试
userSlice.getInitialState().userName
软件包版本: