【问题标题】:react native redux: how do I update a specific value in a slicereact native redux:如何更新切片中的特定值
【发布时间】:2022-01-24 19:59:20
【问题描述】:

这是我的 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)变得未定义。那么如何在不触及其他值的情况下更新单个值呢?

【问题讨论】:

    标签: react-native redux


    【解决方案1】:

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

    目前,您覆盖了nameemailavatarid 属性:

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

    这将只合并包含的属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多