我发现extraReducers
在创建切片时使用该功能createSlice
是最好的方法。
就我而言,我通过为每个相关功能创建一个“SliceFactory”类来实现这一点。我已经使用它来完全执行示例中的操作,并通过侦听LOGOUT_USER
操作来重置用户注销时的相关切片。
参考:
extraReducers:https ://redux-toolkit.js.org/api/createSlice#extrareduce
我用于工厂的原始文章:https ://robkendal.co.uk/blog/2020-01-27-react-redux-components-apis-and-handler-utilities-part-two
import { createSlice } from '@reduxjs/toolkit';
import { LOGOUT_USER } from '../redux/actions';
class CrudReducerFactory {
constructor(slice, state = null, initialState = {}) {
state = state || slice;
this.initialState = initialState;
const reducerResult = createSlice({
name: slice,
initialState: initialState[state],
reducers: this._generateReducers(),
extraReducers: (builder) => {
builder.addCase(LOGOUT_USER, (state, action) => {
return { ...this.initialState };
});
},
});
this.reducer = reducerResult.reducer;
this.actions = reducerResult.actions;
}
_generateReducers = () => {
return {
// Create One
requestCreateOne: (state, action) => {
state.isLoading = true;
},
requestCreateOneSuccess: (state, action) => {
state.isLoading = false;
state.one = action.payload;
},
requestCreateOneError: (state, action) => {
state.isLoading = false;
},
// ...snip...
};
};
}
export default CrudReducerFactory;
这是这样实例化的:
const factory = new CrudReducerFactory('users', 'users', { foo: 'bah', one: null, isLoading: false } );
第一个参数是切片的名称,第二个是状态切片,第三个是初始状态。
然后您可以使用factory.reducer
并factory.actions
相应地使用。