React JS中如何筛选Queryset实现仅展示摩托车分类产品
功能实现修改方案
存在的问题
- 筛选条件错误:你需要展示摩托车类产品,但当前代码的筛选逻辑写的是筛选分类为
Car的产品,自然无法得到预期结果 - 渲染位置错误:摩托车板块的渲染逻辑放在了加载、错误判断逻辑外,接口请求未完成时
products可能为undefined,会触发运行时报错 - 结构不规范:直接用
<li>渲染列表项,外层缺少<ul>包裹,会触发HTML语义化警告
修改方案
- 将filter的判断条件改为你后台产品数据中摩托车分类对应的字段值,示例中统一使用
MotorBike作为分类值,你可以根据实际数据调整 - 把摩托车板块移到加载完成、无报错的逻辑分支内
- 补全列表结构,也可以直接复用上方的Product组件展示样式保持页面统一
修改后完整代码
import React, { useState, useEffect } from 'react' import { Row, Col } from 'react-bootstrap' import Product from '../components/Product' import Loader from '../components/Loader' import Message from '../components/Message' import { useDispatch, useSelector } from 'react-redux' import { listProducts } from '../actions/productActions' import ProductCarousel from '../components/ProductCarousel' function HomeScreen({history}) { const dispatch = useDispatch() const productList = useSelector(state => state.productList) const {error, loading, products} = productList let keyword = history.location.search useEffect(() => { dispatch(listProducts(keyword)) }, [dispatch, keyword]) return ( <div> { !keyword && <ProductCarousel /> } <br /> <h3 ><b><i>Recent Products <i class="fab fa-product-hunt"></i></i></b></h3> <hr /> <br /> {loading ? <Loader /> : error ? <Message variant='danger'>{error}</Message> : <> <Row className='flex flex-wrap' > {products.length === 0 && ( <Col style={{ textAlign: "center" }}> <img src='https://cdn.dribbble.com/users/2382015/screenshots/6065978/no_result.gif' ></img> </Col> )} {products.map(product => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> <br /> <Row> <Col> <h3><b> <i> MotorBike <i class="fas fa-biking"></i></i></b></h3> <hr /> <Row className='flex flex-wrap'> {products.filter(product => product.category === 'MotorBike').map(p => ( <Col key={p._id} sm={12} md={6} lg={4} xl={3}> <Product product={p} /> </Col> ))} </Row> </Col> </Row> </> } </div> ) } export default HomeScreen
如果不需要和上方产品保持一样的卡片样式,只需要展示名称的话,把摩托车板块的渲染逻辑替换为以下代码即可:
<ul> {products.filter(product => product.category === 'MotorBike').map(p => ( <li key={p._id}> {p.name} </li> ))} </ul>
内容的提问来源于stack exchange,提问作者Sohanur Rahman Shanto 16209570
相关产品推荐
相关产品推荐

