对于map函数无法正确检查我的react-redux和redux工具包商店中更新的数组(购物车)中的元素,是否有解决方案?

问题描述 投票:0回答:1

我从产品将产品添加到购物车,并且产品被添加到购物车(因为每个产品都会增加数组的长度),但是当从购物车组件渲染更新的购物车时,它无法正确渲染,并且控制台不断给出错误“警告:列表中的每个孩子都应该有一个唯一的“key”道具。

检查

Cart
的渲染方法。请参阅 https://reactjs.org/link/warning-keys 了解更多信息。 div”。

我使用了各种方法来检查解决方案,但只是发现产品元素(来自 productsinCart 数组)的有效负载可能是未定义的,这就是问题所在,但我在这里可能是错的。

有什么解决问题的建议吗?

cartSlice.js

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

const cartSlice = createSlice({
  name: "cart",
  initialState: [],

  reducers: {
    add(state, action) {
      state.push(action.payload);
    },
    remove(state, action) {
      state.splice(action.payload, 1);
    },
  },
});
`
export const { add, remove } = cartSlice.actions;
export default cartSlice.reducer;

store.js

import { configureStore } from "@reduxjs/toolkit";
import cartReducer from "./Slices/cartSlice";

const store = configureStore({
  reducer: {
    cart: cartReducer,
  },
});

export default store;


产品.js

import React, { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { add } from "../store/Slices/cartSlice";

const Products = () => {
  const [products, setProducts] = useState([]);
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchProducts = async () => {
      const url = "https://fakestoreapi.com/products";

      try {
        const response = await fetch(url);

        const result = await response.json();
        

        setProducts(result);
      } catch (error) {
        console.log("Sorry, there is an error");
      }
    };
    fetchProducts();
  }, []);

  const handleAdd = (product) => {
    dispatch(add(product));
  };

  return (
    <div>
      {products?.map((product) => {
        const { id, image, price, title } = product;

        return (
          <div key={id}>
            <img src={image} alt="" />
            <h4>{title}</h4>
            <h5>{price}</h5>
            <button
              onClick={() => {
                handleAdd(add());
              }}
              
            >
              Add to Cart
            </button>
          </div>
        );
      })}
    </div>
  );
};

export default Products;

Cart.js

import React from "react";
import { useSelector } from "react-redux";
import Layout from "../components/Layout/Layout";

const Cart = () => {
  const productsinCart = useSelector((state) => {
    return state.cart;
  });

  return (
    <Layout>
      <h3>Cart </h3>
      <section>
        <div>
          {productsinCart?.map((product) => {           
            const { id, image, price, title } = product;
            
            return (
              <div key={id}>
                <img src={image} alt="" />
                <p>{title}</p>
                <p>{price}</p>
                <button>Remove</button>
              </div>
            );
          })}
        </div>
      </section>
    </Layout>
  );
};

export default Cart;

注意:我只尝试添加产品并渲染更新的购物车。

reactjs react-redux redux-toolkit
1个回答
0
投票

问题

Products
组件未正确将产品添加到
state.cart
。它不是将当前映射的产品对象传递给
handleAdd
回调,而是调用不带任何负载的
add
操作并传递结果。

const Products = () => {
  const [products, setProducts] = useState([]);
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchProducts = async () => {
      const url = "https://fakestoreapi.com/products";

      try {
        const response = await fetch(url);
        const result = await response.json();
        setProducts(result);
      } catch (error) {
        console.log("Sorry, there is an error");
      }
    };
    fetchProducts();
  }, []);

  const handleAdd = (product) => {
    dispatch(add(product));
  };

  return (
    <div>
      {products?.map((product) => {
        const { id, image, price, title } = product;

        return (
          <div key={id}>
            <img src={image} alt="" />
            <h4>{title}</h4>
            <h5>{price}</h5>
            <button
              onClick={() => {
                handleAdd(add()); // <-- passing action object
              }}
            >
              Add to Cart
            </button>
          </div>
        );
      })}
    </div>
  );
};

因此,不要使用看起来像这样的购物车数组:

[
  { id: "...", image: "...", price: "...", title: "..." },
  { id: "...", image: "...", price: "...", title: "..." },
  { id: "...", image: "...", price: "...", title: "..." },
  ...etc
]

您的购物车数组可能如下所示:

[
  {
    type: "cart/add",
    payload: { type: "cart/add", payload: undefined }
  },
  {
    type: "cart/add",
    payload: { type: "cart/add", payload: undefined }
  },
  {
    type: "cart/add",
    payload: { type: "cart/add", payload: undefined }
  },
  ...etc
]

所有这些购物车数组元素都缺少产品属性,包括用作 React 键的

id
属性。

解决方案

修复很简单,将

product
传递给
handleAdd
处理程序。

const handleAdd = (product) => {
  dispatch(add(product));
};

return (
  <div>
    {products.map((product) => {
      const { id, image, price, title } = product;

      return (
        <div key={id}>
          <img src={image} alt="product" />
          <h4>{title}</h4>
          <h5>{price}</h5>
          <button onClick={() => handleAdd(product)}>
            Add to Cart
          </button>
        </div>
      );
    })}
  </div>
);
© www.soinside.com 2019 - 2024. All rights reserved.