sua*_*kim 6 reactjs redux redux-thunk redux-reducers redux-toolkit
我对整个 React 和 Redux 生态系统相当陌生,我试图了解在使用 Redux 工具包时何时以及为何使用额外的减速器,而不是直接在异步 thunk 中分派操作。
最好用一个显示这两种解决方案的示例来解释:
auth.slice.ts
// ...
export const login = createAsyncThunk<LoginResponse, LoginData>(
'auth/login',
async ({ email, password }, thunkAPI) => {
const data = await AuthService.login(email, password);
// Extract user info from login response which holds other information as well
// in which we're not interested in the auth slice...
const userInfo = loginResponseToUserInfo(data);
LocalStorageService.storeUserInfo(userInfo);
// Return the whole login response as we're interested in the other data
// besides the user info in other slices which handle `login.fulfilled` in
// their own `extraReducers`
return data;
}
);
// ...
const authSlice = createSlice({
// ...
extraReducers: builder => {
builder.addCase(login.fulfilled, (state, { payload }) => {
// Again: Extract user info from login response which holds other
// information as well in which we're not interested in the auth slice...
const userInfo = loginResponseToUserInfo(payload);
return { ...state, userInfo };
}))
// ...
},
});
// ...
Run Code Online (Sandbox Code Playgroud)
auth.slice.ts
// ...
export const login = createAsyncThunk<LoginResponse, LoginData>(
'auth/login',
async ({ email, password }, thunkAPI) => {
const data = await AuthService.login(email, password);
// Extract user info from login response which holds other information as well
// in which we're not interested in the auth slice...
const userInfo = loginResponseToUserInfo(data);
LocalStorageService.storeUserInfo(userInfo);
// !!! Difference to version 1 !!!
// Directly dispatch the action instead of using `extraReducer` to further
// process the extracted user info
thunkAPI.dispatch(authSlice.actions.setUserInfo(userInfo));
// Return the whole login response as we're interested in the other data
// besides the user info in other slices which handle `login.fulfilled` in
// their own `extraReducers`
return data;
}
);
// ...
const authSlice = createSlice({
// ...
reducers: {
setUserInfo: (state, { payload }: PayloadAction<UserInfo>) => ({
...state,
userInfo: payload,
}),
// ...
},
});
// ...
Run Code Online (Sandbox Code Playgroud)
如果我没有完全错的话,这两个例子都做了完全相同的事情,但是通过互联网,我发现大多数人都建议使用选项 1,这extraReducer就是我问的原因:
extraReducers方法”有什么好处吗?loginResponseToUserInfo在两个位置(异步 thunk 和 )执行转换extraReducer,而我只需要在第二个版本中调用它一次......在我看来,两者都是有效的,尽管我个人会选择第一。
为了证明我的选择是正确的:
| 归档时间: |
|
| 查看次数: |
1923 次 |
| 最近记录: |