【问题标题】:Redux toolkit updating state on api responseRedux 工具包在 api 响应上更新状态
【发布时间】:2021-12-11 09:30:49
【问题描述】:

我对 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;
    });
  },

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

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    Redux Toolkit 构建在 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。返回新状态

    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,
      };
    });
    

    返回语法可以简化为:

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2021-06-20
      • 2023-01-16
      • 2021-11-09
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      相关资源
      最近更新 更多