使用redux工具包替换多个切片的状态

zvms9eto  于 2022-11-24  发布在  其他
关注(0)|答案(3)|浏览(167)

如何使用redux工具包在react中将由多个切片组成的存储的状态替换为其他新状态?
您可以使用extraReducers将整个存储恢复到其初始状态:是否可以使用相同的机制将存储状态改变为不同于初始状态的其他状态?
例如,您可能会有如下内容:

const aSlice = createSlice({ 
  name: 'a', 
  initialState: {a: 1}, 
  reducers: {
    someReducer(state, action) {...}
  }
})
const bSlice = createSlice({ 
  name: 'b', 
  initialState: {b: 'foo'}, 
  reducers: {}
})

const store = configureStore({
  reducer: {
    aReducer: aSlice.reducer,
    bReducer: bSlice.reducer,
  }
});

export type RootState = ReturnType<typeof store.getState>

在React元件中,您可以使用以下命令更新状态:

const dispatch = useDispatch();
dispatch(someReducer({...}));

如何将整个商店的状态替换为以下内容:

{
  "aReducer": {"a": 2},
  "bReducer": {"b": "bar"},
}
zkure5ic

zkure5ic1#

您可以使用extraReducer来实现这一点。
你可以传递任意的有效载荷(比如{"a": 2, "b": "bar"})给创建的动作。使用createAction,你可以拥有不“属于”特定切片的动作,请参见:https://redux-toolkit.js.org/api/createAction,并在两个分片中实现extraReducer,这些分片仅使用其有效负载部分。

eblbsuwk

eblbsuwk2#

根据定义,Reducer只能访问他们拥有的状态部分。用户减速器,立柱:postsReducer},则usersReducer根本无法访问posts状态切片。How can I access state of another slice in redux with redux-toolkit?
因此,您必须分派两个切片的两个动作,每个单独的减速器将单独更新其状态。

5f0d552i

5f0d552i3#

正如Dermeck建议的那样,您确实可以将extraReducers * 与 * typesafety一起使用。
一个最小的例子是:

import {combineReducers, configureStore, createAction, createSlice, PayloadAction} from "@reduxjs/toolkit";

export const replaceWith = createAction<RootState>('REPLACE_WITH');

const initialState: { a: number } = {
  a: 0
}

export const aSlice = createSlice({
  name: 'a-slice',
  initialState,
  reducers: {
    reduce(state, action: PayloadAction<number>) {
      return {a: action.payload}
    }
  },
  extraReducers: (builder) => {
    builder.addCase(replaceWith, (_, action) => {
      return {
        ...action.payload.aReducer,
      };
    });
  },
});

export const bSlice = createSlice({
  name: 'b-slice',
  initialState: {},
  reducers: {/* TODO */},
  extraReducers: (builder) => {/* TODO */},
});

const rootReducer = combineReducers({
  aReducer: aSlice.reducer,
  bReducer: bSlice.reducer
});

const store = configureStore({
  reducer: rootReducer,
});

export type RootState = ReturnType<typeof rootReducer>;

最后,在React组件中,您可以执行以下操作:

const dispatch = useDispatch();
dispatch(replaceWith(newState));

相关问题