react native redux:如何更新切片中的特定值

react native redux: how do I update a specific value in a slice

这是我的 redux 配置:

userSlice.js

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

const initialState = {
  name: "",
  email: "",
  avatar: "",
  id: "",
};


export const userSlice = createSlice({
  name: "user",
  initialState: initialState,
  reducers: {
    setUser: (state, action) => {
      return {
        ...state,
        name: action.payload.name,
        email: action.payload.email,
        avatar: action.payload.avatar,
        id: action.payload.id,
      };
    },
  },
});

export const { setUser, logout } = userSlice.actions;
export default userSlice.reducer;

store.js

import { configureStore } from "@reduxjs/toolkit";
import userSlice from "./slices/userSlice";

export const store = configureStore({
    reducer: {
       user: userSlice,
    },
});

app.js

                <Provider store={store}>
                  <Stack.Navigator >
                        <Stack.Screen options={{headerShown: false}} name="Signin" component={Signin} />
                        <Stack.Screen options={{headerShown: false}} name="Home" component={Home} />
                        <Stack.Screen name="Profile" component={Profile} />
                    </Stack.Navigator>
                </Provider>      

下面是一些上下文:

  1. 我登录然后通过fetch

    的响应将值放入用户切片
                             const newUser = {
                               name: oj.name,
                               email: oj.email,
                               avatar: oj.avatar,
                               id: oj.sub,
                             };
                             dispatch(setUser(newUser));
    
  2. 登录后,我console.log这些值是这样的:

    const user = useSelector((state) => state.user);
    console.log(user)   
    

这是它显示的内容:

Object {
  "avatar": "url",
  "email": "asd",
  "id": "61bcf738e954f7ffc11d507d",
  "name": "Asd",
}

我想将 name"name": "Asd" 更新到 "name": "bill" 而不更改其他,这是我的尝试:

const newUser = {                 

 name: "bill"
};
dispatch(setUser(newUser));

它有效,但其他属性(电子邮件、头像、ID)变得未定义。那么如何在不影响其他值的情况下更新单个值?

您可以使用扩展运算符将现有状态与您的新负载合并。

目前,您覆盖了 nameemailavatarid 属性:

return {
        ...state,
        name: action.payload.name,
        email: action.payload.email,
        avatar: action.payload.avatar,
        id: action.payload.id,
      };

这将仅合并包含的属性:

return {
        ...state,
        ...action.payload,
      };