我目前正在使用react、express js和mysql作为数据库构建一个简单的电子商务平台。 现在,当我从数据库检索数据以生成产品时,它会将其自身复制到多个实例中,例如产品 1,然后它将显示为 3 个具有相同名称和 ID 的产品
这是代码
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const ProductCard = ({ product }) => {
const [isEditing, setIsEditing] = useState(false);
const [editedProduct, setEditedProduct] = useState({});
useEffect(() => {
console.log('ProductCard mounted with product:', product);
return () => {
console.log('ProductCard unmounted');
};
}, [product]);
if (!product) {
return <div>Product data is not available</div>;
}
const handleEditClick = () => {
setIsEditing(true);
setEditedProduct(product); // Pre-fill form with current product data
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setEditedProduct(prevState => ({
...prevState,
[name]: value,
}));
};
const handleUpdate = async () => {
try {
await axios.put(`http://localhost:5000/products/${product.product_id}`, editedProduct);
alert('Product updated successfully');
setIsEditing(false);
} catch (error) {
console.error('Error updating product:', error);
alert('Error updating product');
}
};
return (
<div className='procard'>
<div className='productimg' style={{ width: '100%', height: '65%' }}>
<img
style={{ width: '98%', height: '100%', objectFit: 'cover' }}
src={product.image_url || 'https://via.placeholder.com/150'}
alt={product.product_name || 'Product Image'}
/>
</div>
<div className='productdesc' style={{ width: '100%', height: '35%' }}>
{isEditing ? (
<div className='product-edit'>
<input
type='text'
name='product_name'
value={editedProduct.product_name || ''}
onChange={handleInputChange}
placeholder='Product Name'
/>
<textarea
name='description'
value={editedProduct.description || ''}
onChange={handleInputChange}
placeholder='Description'
/>
<input
type='number'
name='quantity'
value={editedProduct.quantity || ''}
onChange={handleInputChange}
placeholder='Quantity'
/>
<input
type='number'
name='size'
value={editedProduct.size || ''}
onChange={handleInputChange}
placeholder='Size (ml)'
/>
<button onClick={handleUpdate}>Update Product</button>
<button onClick={() => setIsEditing(false)}>Cancel</button>
</div>
) : (
<div className='product-data'>
<p>{product.product_name || 'No product name'}</p>
<div className='order-options'>
<button>Add to Cart</button>
<button>Buy Now</button>
<button onClick={handleEditClick}>Edit Product</button>
</div>
</div>
)}
</div>
</div>
);
};
const ProductList = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
console.log('ProductList mounted');
const fetchProducts = async () => {
try {
const response = await axios.get('http://localhost:5000/products');
if (response.status === 200) {
console.log('Fetched products:', response.data);
const uniqueProducts = Array.from(new Map(response.data.map(product => [product.product_id, product])).values());
setProducts(uniqueProducts);
} else {
throw new Error(`Unexpected response status: ${response.status}`);
}
} catch (error) {
console.error('Error fetching products:', error.response ? error.response.data : error.message);
setError('Error fetching products: ' + (error.response ? error.response.data : error.message));
} finally {
setLoading(false);
}
};
fetchProducts();
return () => {
console.log('ProductList unmounted');
};
}, []); // Empty dependency array to ensure effect runs only once on mount
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>{error}</div>;
}
return (
<div className='product-list'>
{products.length > 0 ? (
products.map(product => (
<ProductCard key={product.product_id} product={product} />
))
) : (
<div>No products available</div>
)}
</div>
);
};
export default ProductList;
我确实尝试控制台记录它,以便我可以查看查询是否正常工作并且到目前为止没有复制数据
但是在我的朋友看来,这就是问题
这是我的后端查询
app.get('/products', async (req, res) => {
try {
const [rows] = await db.query('SELECT * FROM product');
const uniqueProducts = Array.from(new Map(rows.map(product => [product.product_id, product])).values());
console.log('Fetched unique products:', uniqueProducts);
res.json(uniqueProducts);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).send('Error fetching products');
}
});
我希望每当我显示数据库中的数据时,就不会有重复的数据
使用 set 删除重复值。
const products = []
const uniqueProducts = [new Set(...products)]
console.log(uniqueProducts) // No duplicate value