繁体   English   中英

如何在 react.js 中使用两个条件进行过滤

[英]how to filter with two condition in react.js

我正在尝试使用 react-bootstrap 创建一个电子商务网站,对于我的产品详细信息页面,我想根据用户选择的具有不同 ID 和类别的项目显示产品。 我想过滤所以它只显示具有相同 id 和类别的项目,但它不起作用它仍然只根据它们的类别显示所有项目。 我希望它基于类别和 id。 我该如何解决?

我的代码:

const ProductList = () => {
  const { category, id } = useParams()
  const[productList, setProductList]= useState();

  useEffect(() =>{
    axios.get(`https://fakestoreapi.com/products`).then(res => {
        const products = res.data;
        var filteredCategory =
        products.filter((productList) =>
        productList.category === category || productList.id === id)
        setProductList(filteredCategory)
      })
  }, []);

  console.log()

  return (
    <>
      <Container fluid>
        
          {productList && productList.map(product =>{
            const {id, title, price, category,image} = product;
            return(
              <Row>
                <Col lg={3} className="d-flex">
                  <img src={image} width="50%"></img>
                </Col>

                <Col>
                  <h1> {title}</h1>
                </Col>
              </Row>
            )
          })}
      </Container>
    </>
  )
}

API响应中的product idnumber类型, useParams中提取的idstring类型。 使用==而不是===进行比较时,您可以忽略类型。 如果您打算在满足两个条件的情况下进行过滤,那么它应该是&&而不是|| .

代替

productList.category === category || productList.id === id

尝试

productList.category === category && productList.id == id

编辑 zealous-lamarr-hyyb0e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM