| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import { useEffect, useMemo } from 'react';
- import { Fragment } from 'react'
- import { getAllProducts } from '../api/product';
- import { useDispatch, useSelector } from 'react-redux';
- import { fetchProduct, setShowStock, setFilterName } from '../store/slice/productSlice';
- function Product() {
- const dispatch = useDispatch();
- useEffect(() => {
- dispatch(fetchProduct())
- }, [dispatch])
- const { products, filterName, showStock } = useSelector(x => x.productSlice);
- const filterProducts = useMemo(() => {
- return products.filter(item => item.name.includes(filterName) && (showStock ? item.stocked : true))
- }, [products, filterName, showStock])
- const renderProduct = () => {
- let prevCategory = ''
- return filterProducts.map((product, index) => {
- const showCategoryHeader = prevCategory !== product.category
- prevCategory = product.category
- return (
- <Fragment key={product.name + index}>
- {showCategoryHeader && (
- <tr style={{ background: '#e8f0fe' }}>
- <td colSpan={2}>
- <strong>{product.category}</strong>
- </td>
- </tr>
- )}
- <tr>
- <td>
- <span style={{ color: product.stocked ? '#333' : '#e74c3c' }}>
- {product.name}
- </span>
- {!product.stocked && (
- <span style={{ color: '#e74c3c', fontSize: 12, marginLeft: 8 }}>
- (缺货)
- </span>
- )}
- </td>
- <td>{product.price}</td>
- </tr>
- </Fragment>
- )
- })
- }
- return (
- <div>
- <h1>📦 商品列表</h1>
- <div style={{ margin: '16px 0', display: 'flex', gap: 16, alignItems: 'center' }}>
- <input type="text" placeholder='搜索商品名称...' onChange={(e) => dispatch(setFilterName(e.target.value))} style={{ padding: '8px 12px', borderRadius: 6, border: '1px solid #d9d9d9', width: 240 }} />
- <label style={{ cursor: 'pointer' }}>
- <input type="checkbox" style={{ marginRight: 6 }} onChange={(e) => dispatch(setShowStock(e.target.checked))} />仅显示有库存的商品</label>
- </div>
- <table border={1} cellPadding={12} style={{ borderCollapse: 'collapse', width: '100%' }}>
- <thead>
- <tr style={{ background: '#1a73e8', color: '#fff' }}>
- <th>商品名称</th>
- <th>商品价格</th>
- </tr>
- </thead>
- <tbody>
- {filterProducts.length === 0 ? (
- <tr>
- <td colSpan={2} style={{ textAlign: 'center', padding: 40, color: '#999' }}>
- 📭 暂无匹配商品
- </td>
- </tr>
- ) : (
- renderProduct()
- )}
- </tbody>
- </table>
- </div>
- )
- }
- export default Product;
|