reactjs 多类别React过滤器

k2fxgqgv  于 2022-12-29  发布在  React
关注(0)|答案(1)|浏览(169)
const [product, setProduct] = useState([]);
const [filters, setFilters] = useState({
    category: '',
    brand: '',
    type: '',
  });
const displayProduct = product
.filter(prod =>
    prod.category.includes(filters.category) &&
    prod.brand.includes(filters.brand) &&
    prod.type.includes(filters.type)
  )
.map(product => {
    return(
        <div className='imageContainer ' key={product.id}>
            <img src={PopularOne} className="image"/>
            <div className='productName'>
            <Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
            </div>
            <div className='productPrice'>
            <h3 >RM{product.productPrice}</h3>
            </div>
        </div>   
    )
})
<input type="checkbox"  onClick={() => {setFilters({...filters,category: 'abc',})}}/><label>abc</label><br/>
<input type="checkbox"  onClick={() => {setFilters({...filters,category: 'test',})}}/><label>test</label>

我有一个过滤器,可以过滤产品的类别,品牌,和类型。我面临的问题是我只能过滤一个类别的时间,我想选择多个类别和过滤多个类别的时间。我该怎么做?

prdp8dxp

prdp8dxp1#

  • 更新输入
  • 已添加句柄筛选器
  • 已更新setFilters使用状态
  • 更新的乘积滤波器
const [product, setProduct] = useState([]);
const [filters, setFilters] = useState({
    category: [],
    brand: [],
    type: [],
  });
const handleFilter = (filterType, filterValue) => {
  const isAvailable = filters[filterType].includes(filterValue)
  setFilters({
    ...filters,
    [filterType]: isAvailable ? filters[filterType].filter(item => item !== filterValue) : [...filters[filterType], filterValue]
  })
}
const displayProduct = product
.filter(prod =>
    prod.category.some(item => item.includes(filters.category)) &&
    prod.brand.some(item => item.includes(filters.brand)) &&
    prod.type.some(item => item.includes(filters.type))
  )
.map(product => {
    return(
        <div className='imageContainer ' key={product.id}>
            <img src={PopularOne} className="image"/>
            <div className='productName'>
            <Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
            </div>
            <div className='productPrice'>
            <h3 >RM{product.productPrice}</h3>
            </div>
        </div>   
    )
})
<input type="checkbox"  onClick={() => {handleFilter({'category', 'abc'})}}/><label>abc</label><br/>
<input type="checkbox"  onClick={() => {handleFilter({'category', 'test'})}}/><label>test</label>

相关问题