【问题标题】:Can't append reducer state in redux toolkit无法在 redux 工具包中附加 reducer 状态
【发布时间】:2022-10-02 10:14:00
【问题描述】:

我想用 action.payload 附加 state.data,我已经尝试了它在 .concat、.push 或在数组中传播的所有内容。

import { createAction, createReducer } from \"@reduxjs/toolkit\";
    const initialState = {};
    const request = createAction(\"allDataRequest\");
    const success = createAction(\"allDataSuccess\");
    const fail = createAction(\"allDataFailure\");
    const clear = createAction(\"clearErrors\");
    
    export const allServicesReducer = createReducer(initialState, (builder) => {
      builder
        .addCase(request, (state, action) => {
          state.loading = true;
        })
        .addCase(success, (state, action) => {
          state.loading = false;
          state.data = action.payload;
          // I want to append this state.data with payload
          //state.data = state.data.concat(action.payload)
          //state.data = [...state.data, ...action.payload]
          // However i get stae.data undefined on both
        })
        .addCase(fail, (state, action) => {
          state.loading = false;
          state.error = action.payload;
        })
        .addCase(clear, (state, action) => {
          state.error = null;
        });
    });

    标签: react-native redux react-redux redux-toolkit


    【解决方案1】:

    这是因为你的初始状态是不是有一个.data 字段

     const initialState = {};
    

    所以,是的,一开始它会是空的。

    您需要提供const initialState = {data: []} 所以那里一个字段,或者更新 reducer 逻辑来处理它不存在的情况。

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2022-08-14
      • 2020-11-17
      • 2023-03-23
      相关资源
      最近更新 更多