我一直在建立一个电子商务网站。将商品添加到购物卡后出现问题。我已成功将商品添加到卡中,但是问题是当我单击“继续购物”按钮时,我导航到“产品”页面,但是产品无法像以前一样正确显示。
我附上了图片:当我单击购物车按钮时,将打开一个模式,当我单击“继续购物”时,出现另一个屏幕,并且在控制台中出现此错误:
index.js:1375 Warning: Failed prop type: Invalid prop `product` of type `array` supplied to `Product`, expected `object`.
in Product (at ProductList.js:42)
in div (at ProductList.js:38)
in div (at ProductList.js:34)
in section (at ProductList.js:33)
in ProductList (created by Context.Consumer)
in Route (at App.js:20)
in Switch (at App.js:19)
in App (at src/index.js:12)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:11)
in ProductProvider (at src/index.js:10)
console.<computed> @ index.js:1375
index.js:1375 Warning: Each child in a list should have a unique "key" prop. See /react-warning-keys for more information.
in div (at ProductList.js:38)
in div (at ProductList.js:34)
in section (at ProductList.js:33)
in ProductList (created by Context.Consumer)
in Route (at App.js:20)
in Switch (at App.js:19)
in App (at src/index.js:12)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:11)
in ProductProvider (at src/index.js:10)
console.<computed> @ index.js:1375
index.js:1375 Warning: Each child in a list should have a unique "key" prop. See react-warning-keys for more information.
in div (at ProductList.js:38)
in div (at ProductList.js:34)
in section (at ProductList.js:33)
in ProductList (created by Context.Consumer)
in Route (at App.js:22)
in Switch (at App.js:19)
in App (at src/index.js:12)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:11)
in ProductProvider (at src/index.js:10)
console.<computed> @ index.js:1375
我在网上找不到任何相关问题或项目。这是我的第一个大型React项目,希望在这里找到解决方案。
Context.js
getItem = id => {
const product = this.state.products.find(item => item.id === id);
return product;
};
addToCart = id => {
const tempProducts = [...this.state.products];
const index = tempProducts.indexOf(this.getItem(id));
const product = tempProducts[index];
product.inCart = true;
product.count = 1;
const price = product.price;
product.total = price;
this.setState(
() => {
return {
products: [tempProducts],
cart: [...this.state.cart, product],
detailProduct: { ...product }
};
},
() => this.addTotals()
);
};
我认为问题在于选择商品并在“ addToCart”方法中进行修改。我知道,如果需要修改列表中的项目,我也必须专门找到其索引,否则项目将无法像现在一样正确显示。