首页 > 解决方案 > React-Redux:如何从数组中添加每个项目

问题描述

我当前的调度实现

我尝试通过映射来调度项目,但有时 Redux 会给出未定义的错误,所以我想在 reducer 中尝试更好的方法。

const dispatch = useDispatch()
const mapCheck =  [
    "Math",
    "Spanish",
    "Clean garden",
]

mapCheck.map(c=>dispatch(createCustomList(c.val)))

我想要做什么

我正在尝试从数组中获取每个单独的项目以进行分派,但是我得到了这个输出我有一个待办事项列表,我在其中分派了一个数组,如下所示:

我的减速机

import { CUSTOM_LIST } from "../actions/shoppingList";

const initialState = { 
    myCustomItems: []
};

const ToDoReducer = (state = initialState, action) => {
    switch (action.type) {
        case CUSTOM_LIST:
            const customList = { id: Date.now(),val: action.custom.custom};

            const custom = state.myCustomItems.concat(customList);

            const existingCustomItem = state.myCustomItems.findIndex(
                item => item.val === action.custom.custom
            );
            if (existingCustomItem >= 0) {
                return {...state, myCustomItems: state.myCustomItems}
            } else {
                return {...state,myCustomItems: custom};
            }
        default:
            return state;
    }
};

export default ToDoReducer;

期望的输出

如何映射每个项目并在所需输出中添加如下所示的 id。不用担心 id 只是Date.now()

所需的输出:

const DesiredOutput = [{
        "id": "qm6a67ci",
        "val": "Math",
    },
    {
        "id": "qm6a62ci",
        "val": "Spanish",
    },
    {
        "id": "rkrkmroepe",
        "val": "Clean garden",
    }
]

标签: javascriptreactjsreduxreact-redux

解决方案


请使用以下代码。希望它能解决您的问题。

import { CUSTOM_LIST } from "../actions/shoppingList";

const initialState = { 
    myCustomItems: []
};

const ToDoReducer = (state = initialState, action) => {
    switch (action.type) {
        case CUSTOM_LIST:
            const customList = { id: Date.now(),val: action.custom.custom};

            const existingCustomItem = state.myCustomItems.findIndex(
                item => item.val === action.custom.custom
            );
            if (existingCustomItem > -1) {
                return {...state, myCustomItems: state.myCustomItems}
            } else {
                return {...state,myCustomItems: [...state.myCustomItems,customList ]};
            }
        default:
            return state;
    }
};

export default ToDoReducer;

或者您可以做的第二种方法是,您可以分派单个动作,而不是分派多个动作

下面的代码将从数组中删除重复项,因此您不必在减速器中添加条件

const dispatch = useDispatch()
const mapCheck =  [
    "Math",
    "Spanish",
    "Clean garden",
]

dispatch(createCustomList[...new Set(mapCheck)]))

减速机文件

import { CUSTOM_LIST } from "../actions/shoppingList";

const initialState = {
  myCustomItems: [],
};

const ToDoReducer = (state = initialState, action) => {
  switch (action.type) {
    case CUSTOM_LIST:
      return {
        ...state,
        myCustomItems: action.customList.map((val) => ({
          id: Date.now(),
          val,
        })),
      };

    default:
      return state;
  }
};

export default ToDoReducer;

推荐阅读