Redux Toolkit -无法更新等于null的初始状态

kknvjkwl  于 2022-12-19  发布在  其他
关注(0)|答案(2)|浏览(135)

使用Redux工具包的Redux持久化得到奇怪的行为。我不能更新用户的初始状态,如果它是空的。这段代码总是设置空的存储regrindless传递参数。

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { IUser, Nullable } from "../../types";

const initialState = null as Nullable<IUser>  

export const userSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        set(state, action: PayloadAction<IUser>){
            state = action.payload
        }
    }
})

export default userSlice.reducer;

但是,如果初始状态看起来像下面所有的工作正常。我想知道为什么。

const initialState = {
    user: null as Nullable<IUser>  
}
oxcyiej7

oxcyiej71#

最后还是这样做了,不知道是不是合适的解决方案

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Nullable, User } from "../../../types";

const initialState = null as Nullable<User>;

export const userSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        set(state, action: PayloadAction<User>){
            return state ? {...state, ...action.payload} :  action.payload;
        },
        setToken(state, action: PayloadAction<User['token']>){
            state && (state.token = action.payload)
        },
        setUsername(state, action: PayloadAction<User['username']>){
            state && (state.username = action.payload)
        },
        unset(){
            return initialState
        }
    }
})

export default userSlice.reducer;
whitzsjs

whitzsjs2#

当处理一个初始的和偶尔未定义的/null对象时,我通常这样做:

import {
  createSlice
} from "@reduxjs/toolkit";

const currentFoodSlice = createSlice({
  name: "currentFood",
  initialState: {
    value: undefined
  },
  reducers: {
    setCurrentFood: (state, action) => {
      state.value = action.payload;
    },
  },
});

export const {
  setCurrentFood
} = currentFoodSlice.actions;

export const currentFoodReducer = currentFoodSlice.reducer;

相关问题