Redux 工具包 - 更新对象中的键值

Redux toolkit - update a key value in an object

我需要一些帮助来修改我的减速器。我正在使用 Redux Toolkit 并且在其中一个状态切片中我有一个具有一些分组设置的对象:

initialState: {
    ...
    userSettings: {mode: 2, subscription: false, setting3: 'text', setting4: 'another text'},
    ...
}

我有一个减速器是:

setUserSettings: (state, action) => {
    state.userSettings: action.payload
}

在组件的不同部分,我会从 userSettings 对象更新各个设置:

dispatch(setUserSettings({ mode: 4 }))

在另一个地方:

dispatch(setUserSettings({ setting3: 'some other text'})

我如何修改减速器才能做到这一点?谢谢

将您的减速器更改为

setUserSettings: (state, action) => {state.userSettings={...state.userSettings,action.payload}}

我们在这里所做的是复制旧状态,然后将其与您需要更改的新值结合起来 对象的新键将覆盖旧键

由于RTK底层使用了immer库,你可以通过直接赋值来改变状态。参见 Mutating and Returning State

import { configureStore, createSlice } from '@reduxjs/toolkit';

const settingsSlice = createSlice({
  name: 'settings',
  initialState: {
    otherSettings: { ok: true },
    userSettings: { mode: 2, subscription: false, setting3: 'text', setting4: 'another text' },
  },
  reducers: {
    setUserSettings: (state, action) => {
      state.userSettings = { ...state.userSettings, ...action.payload };
    },
  },
});
const { setUserSettings } = settingsSlice.actions;

const store = configureStore({ reducer: settingsSlice.reducer });

store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch(setUserSettings({ mode: 4 }));
store.dispatch(setUserSettings({ setting3: 'some other text' }));

输出:

{
  otherSettings: { ok: true },
  userSettings: {
    mode: 4,
    subscription: false,
    setting3: 'text',
    setting4: 'another text'
  }
}
{
  otherSettings: { ok: true },
  userSettings: {
    mode: 4,
    subscription: false,
    setting3: 'some other text',
    setting4: 'another text'
  }
}