Redux 工具包在 api 响应上更新状态

Redux toolkit updating state on api response

我对 redux 和 reduxjs/toolkit 还很陌生,在 api 调用成功后我一直坚持更新状态。我正在关注此处的文档 -> https://redux-toolkit.js.org/api/createAsyncThunk

import { createSlice } from '@reduxjs/toolkit';
import { loginUser } from './actions';

const userSlice = createSlice({
  name: 'user',
  initialState: { id: 0, name: '', email: '' },
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(loginUser.fulfilled, (state, action) => {
      // trying to overwrite the state directly like this doesn't work
      state = { ...action.payload }
      // updating each individual part of the state object does work, but this is not ideal for scalability
      // state.id = action.payload.id;
      // state.name = action.payload.name;
      // state.email = action.payload.email;
    });
  },

如评论中所述,尝试覆盖整个状态对象是行不通的。没有错误消息,但没有任何反应。但是,更新状态对象的每个单独部分确实有效。

Redux 工具包构建于 Immer 之上。 Immer 允许您以两种方式更新状态。

重要提示:请谨慎选择其中之一,切勿同时选择两者。

1。变异状态

builder.addCase(loginUser.fulfilled, (state, action) => {
  state.id = action.payload.id;
  state.name = action.payload.name;
  state.email = action.payload.email;
  // NEVER use return when mutating state
});

2。 Return 新状态

builder.addCase(loginUser.fulfilled, (state, action) => {
  // NEVER mutate state when using return
  return {
    id: action.payload.id,
    name: action.payload.name,
    email: action.payload.email,
  };
});

return 语法可以简化为:

builder.addCase(loginUser.fulfilled, (state, action) => action.payload);

但我不推荐。我认为您最好明确说明减速器中的状态变化。它使您更容易了解正在发生的变化。