【问题标题】:react native redux toolkit filter not working反应本机 redux 工具包过滤器不起作用
【发布时间】:2021-06-25 15:05:56
【问题描述】:

为什么我的过滤功能不起作用?

ShipperSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { current } from '@reduxjs/toolkit';

const createProductShipper = createSlice({
  name: "createProductShipper",
  initialState: {
    shippers: []
  },
  reducers: {
    AddProductShipper: (state, action) => {
      const shipperExists = state.shippers.find(el => el?.id === action.payload.id);
      if(typeof shipperExists !== 'undefined') {
        return state.shippers.filter(el => el.id !== action.payload.id);
      } else {
        state.shippers.push(action.payload)
      }
      console.log(current(state.shippers));
    },
  }
});

export const { AddProductShipper, RemoveProductShipper } = createProductShipper.actions;

export default createProductShipper.reducer;

这是推送输出

Array [
  Object {
    "id": 1,
    "shipper": "SHIPPER",
  },
]

如果托运人存在,那么我会收到此错误: ....................

TypeError: undefined is not an object (evaluating 'state.shippers.find')

为什么我的托运人对象被删除了?

The State:
Object {
  "shippers": Array [],
}
First Click: 
Object {
  "shippers": Array [
    Object {
      "id": 1,
      "shipper": "DHL",
    },
  ],
}
Second Click:
Array []

.................................................. ......

【问题讨论】:

    标签: react-native redux expo redux-toolkit


    【解决方案1】:

    更改return state.shippers.filter(el => el.id !== action.payload.id);

    收件人:state.shippers = state.shippers.filter(el => el.id !== action.payload.id);

    【讨论】:

    • 非常感谢!它现在是否不可变?
    • Redux Toolkit 的 createReducer 和 createSlice 在内部自动使用 Immer,让您使用“mutating”语法编写更简单的 immutable 更新逻辑。 redux-toolkit.js.org/usage/immer-reducers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    相关资源
    最近更新 更多