简体   繁体   English

如何使用 react reducer 获取单个 object?

[英]How to get a single object by using react reducers?

I found this tutorial https://www.digitalocean.com/community/tutorials/react-crud-context-hooks that describes how to build CRUD app with react hooks and context API.我发现这个教程https://www.digitalocean.com/community/tutorials/react-crud-context-hooks描述了如何使用反应钩子和上下文构建 CRUD 应用程序 API。

Provided that state is described as array with object and in appReducer we have operations:假设 state 被描述为带有 object 的数组,并且在 appReducer 中我们有操作:

  • create创造
  • edit编辑
  • remove is it possible to have also a get method that would return a single object if id is matched with payload.id?如果 id 与 payload.id 匹配,是否有可能还有一个 get 方法返回单个 object?
const initialState = {
  products: [
    {
      id: 1,
      name: "Milk",
      amount: 3,
      company: "XXX"
    }
  ]
};

export default function appReducer(state, action) {
  switch (action.type) {
    case "ADD_PRODUCT":
      return {
        ...state,
        products: [...state.product, action.payload],
      };

    case "EDIT_PRODUCT":
      const updatedProduct = action.payload;

      const updatedProducts = state.products.map((prod) => {
        if (product.id === updatedProduct.id) {
          return updatedProduct;
        }
        return prod;
      });

      return {
        ...state,
        products: updatedProducts,
      };

    case "REMOVE_PRODUCT":
      return {
        ...state,
        products: state.products.filter(
          (prod) => prod.id !== action.payload
        ),
      };

    default:
      return state;
  }
};

What came to my mind is adding selectedProduct property in initialState however I everytime it was required to return products array as well.我想到的是在 initialState 中添加 selectedProduct 属性,但是我每次都需要返回产品数组。

Also I was thinking about adding additional reducer however, I have a synchronization problem with this solution and selectedProduct is returned is out of date.我也在考虑添加额外的 reducer,但是这个解决方案存在同步问题,返回的 selectedProduct 已过时。

Based on my understanding of the question I believe you are trying to fetch a single product from the list.根据我对这个问题的理解,我相信您正在尝试从列表中获取单个产品。 Well you can add a case for that in your reducer like 'GET_SINGLE_PRODUCT'.那么你可以在你的减速器中添加一个案例,比如“GET_SINGLE_PRODUCT”。

export default function appReducer(state, action) {
  switch (action.type) {
          
    case "GET_SINGLE_PRODUCT":
      return {
        ...state,
        product: state.products.find(
          (prod) => prod.id === action.payload
        ),
      };

    default:
      return state;
  }
};

In State State

const initialState = {
  products: [
    {
      id: 1,
      name: "Milk",
      amount: 3,
      company: "XXX"
    }
  ],
product: {}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM