上下文api reducer中的``将新项目添加到类别''功能

问题描述

请参阅沙箱以供参考。

我正在尝试创建一项功能,以“将商品添加到当前类别中”。该代码段的工作方式是,例如,如果添加一个名为“ cars”的类别,它将添加该类别,但同时也会出现在要添加到当前类别的项目的下方。现在,我有一个认值,说“ BMW”,怎么写一个添加到特定类别的函数?我已经在我的context/reducer.ts中存储了一个添加类别”功能,理想情况下,我会使用页面底部的Additem函数Types.AddIitem下的其中添加功能,以提供有效载荷。

这是我的代码

reducer.ts

type ActionMap<M extends { [index: string]: any }> = {
  [Key in keyof M]: M[Key] extends undefined
    ? {
        type: Key;
      }
    : {
        type: Key;
        payload: M[Key];
      };
};

export enum Types {
  Create = "CREATE_CATEGORY",AddItem = "ADD_ITEM"
}

type CategoryType = {
  id: number;
  title: string;
};

type CategoryPayload = {
  [Types.Create]: {
    id: number;
    title: string;
  };
  [Types.AddItem]: {
    id: number;
    subCategories: [any];
  };
};

export type CategoryActions = ActionMap<CategoryPayload>[keyof ActionMap<
  CategoryPayload
>];

export const categoryReducer = (
  state: CategoryType[],action: CategoryActions
) => {
  switch (action.type) {
    case Types.Create:
      // return current state if empty
      if (!action.payload) {
        return state;
      }
      // return current state if duplicate
      if (state.includes(action.payload)) {
        return state;
      }
      return [
        ...state,{
          id: Math.floor(Math.random() * 999999),title: action.payload,subCategories: ["BMW"]
        }
      ];
    case Types.AddItem:

    default:
      return state;
  }
};

export function AddCategory(category) {
  return { type: Types.Create,payload: category };
}

export function AddItem(id,value) {}

context.tsx

import React,{ createContext,dispatch,useReducer } from "react";
import { categoryReducer,CategoryActions } from "./reducer";

// Store Context is the global context that is managed by reducers.
type CategoryType = {
  id: number;
  title: string;
};

type InitialStateType = {
  categories: CategoryType[];
};

const initialState = {
  categories: []
};

const AppContext = createContext<{
  state: InitialStateType;
  dispatch: dispatch;
}>({
  state: initialState,dispatch: () => null
});

const mainReducer = (
  { categories }: InitialStateType,action: CategoryActions
) => ({
  categories: categoryReducer(categories,action)
});

const AppProvider: React.FC = ({ children }) => {
  const [state,dispatch] = useReducer(mainReducer,initialState);

  return (
    <AppContext.Provider value={{ state,dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export { AppProvider,AppContext };

CategoryList.tsx

import React,{ useContext,useState } from "react";
import { AppContext } from "../Context/context";
import "../css/Main.scss";
import pen from "../images/pen.png";
import plus from "../images/plus.png";
import { AddItem } from "../Context/reducer";

interface CategoryProps {
  id: number;
}

function CategoryList() {
  const { state,dispatch } = useContext(AppContext) || [];

  const handleAdd = (props: CategoryProps) => {
    const { id } = props;
    let add = prompt("Enter new item name");

    if (add != null) {
      dispatch(AddItem(id,add));
    }
  };

  console.log(state);

  return (
    <div className="container">
      {state.categories.map(category => {
        return (
          <div key={category.id}>
            <div className="title">
              <strong>{category.title}</strong>
              <input
                type="image"
                alt="Edit your todo"
                src={pen}
                title="Edit todo"
              />
              <input
                type="image"
                alt="add to category"
                src={plus}
                title="Add to category"
                onClick={() => handleAdd(category.id)}
              />
            </div>
            <ul>
              <li>{category.subCategories || [].map(item => item)}</li>
            </ul>
          </div>
        );
      })}
    </div>
  );
}

export default CategoryList;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)