gpt4 book ai didi

javascript - 尝试过滤产品列表时 react "TypeError: product.name.includes(...).map is not a function"

转载 作者:行者123 更新时间:2023-11-28 16:45:01 24 4
gpt4 key购买 nike

我有一个 React 应用程序,当使用 axios.get 调用从数据库获取产品数据时,它会显示产品列表。该部分工作完美,但今天我尝试实现一个搜索功能,仅显示与搜索查询匹配的产品名称,但当我尝试键入哪怕一个字母时,应用程序都会崩溃,我得到以下信息:

TypeError: product.name.includes(...).map is not a function

function productList() {
40 | if(searchTerm) {
> 41 | return products.filter(product => product.name.includes(searchTerm).map(function(currentProduct, i) {
| ^ 42 | return <Product product={currentProduct} key={i} />;
43 | }));
44 | } else {

我怎样才能正确地实现这个?我试图关注this之前回答过的问题作为指导。

productListPublic.js:

import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { CardColumns, Card, Row, Col, ListGroup, Form } from "react-bootstrap";
import axios from "axios";

function ProductListPublic(props) {
const [isError, setIsError] = useState(false);
const [products, setProducts] = useState([]);
const [searchTerm, setSearchTerm] = useState("");

const Product = props => (
<Card>
<Row>
<Col md={{ span: 4 }}>
<Card.Title className="mt-4 text-center">
<Link to={`/products/list/${props.product._id}/`}>{props.product.name}</Link>
</Card.Title>
</Col>
<Col md={{ span: 8 }}>
<ListGroup>
<ListGroup.Item className="text-truncate">{props.product.description}</ListGroup.Item>
<ListGroup.Item>{props.product.stock} in stock</ListGroup.Item>
</ListGroup>
</Col>
</Row>
</Card>
)

useEffect(() => {
axios.get("http://localhost:4000/products/")
.then(res => {
setProducts(res.data);
}).catch(function(err) {
setIsError(true);
})

}, []);

function productList() {
if(searchTerm) {
return products.filter(product => product.name.includes(searchTerm).map(function(currentProduct, i) {
return <Product product={currentProduct} key={i} />;
}));
} else {
return products.map(function(currentProduct, i) {
return <Product product={currentProduct} key={i} />;
})
}
}

return (
<div className="text-center">
<Form>
<Form.Row>
<Form.Group as={Col}>
<Form.Label htmlFor="formSearch">Search Products</Form.Label>
<Form.Control
controlid="formSearch"
type="text"
value={searchTerm}
onChange={e => {
setSearchTerm(e.target.value);
}}
placeholder="Product Name"
/>
</Form.Group>
</Form.Row>
</Form>
<h2>Products List</h2>
<CardColumns>
{ productList() }
</CardColumns>
{ isError &&<p>Something went wrong with getting the products!</p> }
</div>
)
}

export default ProductListPublic;

最佳答案

关闭filter括号,然后在结果列表上使用map

return products.filter(product => product.name.includes(searchTerm)).map((currentProduct, i) => {
return <Product product={currentProduct} key={i} />;
});

关于javascript - 尝试过滤产品列表时 react "TypeError: product.name.includes(...).map is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60645892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com