【问题标题】:Although sometimes it works, I get ".filter is not a function" in my React project虽然有时它有效,但我在我的 React 项目中得到“.filter 不是函数”
【发布时间】:2021-08-19 22:02:31
【问题描述】:
  28 | <Grid.Row>
  29 |   {cars.map((car) => (
  30 |     <Grid.Column style={{marginBottom:"1em"}}>
> 31 |       <CarComponent car={car} imagePath={carImages.filter(image=>image.car.id===car.id)[0].imagePath}></CarComponent>
     | ^  32 |       
  33 |     </Grid.Column>
  34 |   ))}

我从不同的服务(carController、carImageController)获取信息(品牌、颜色、描述等)和车辆照片。因此,在尝试列出汽车时,我会在汽车列表中的每辆汽车的照片列表中选择 carId 等于该汽车 ID 的照片。我将 imagePath 写为 carImages.filter(image=>image.car.id===car.id)[0].imagePath} 以检查来自我的照片服务的数据并将其作为道具发送到汽车零件。有时当一切正常时我会得到这个 typeError 。为什么会这样?

汽车功能组件:

 export default function CarComponent({ car, imagePath}) {
return (
<div>
  <Card style={{height:"388px"}}>
    <Image 
      src={imagePath}
      wrapped
      ui="false"
      style={{height:"200px"}}
      
    />
    <Card.Content>
      <Card.Header>{car.brand.name}</Card.Header>
      <Card.Meta>
        <span className="date">{car.modelYear}</span>
      </Card.Meta>
      <Card.Description>{car.description}</Card.Description>
    </Card.Content>
    <Card.Content extra style={{color:"black"}} >
      <h3 >{car.dailyPrice} ₺</h3>

      <Button secondary animated>
        <Button.Content visible>Kirala</Button.Content>
        <Button.Content hidden>
          <Icon name="arrow right" />
        </Button.Content>
      </Button>
    </Card.Content>
  </Card>
</div>
);}

汽车图像类

export default class CarImageService{
getCarImages(){
    return axios.get("http://localhost:8080/api/images/getAll")
}
}

汽车列表页面

export default function CarsList() {


const [cars, setCars] = useState([]);

  const [carImages, setCarImage] = useState({});

  useEffect(() => {
    let carImageService = new CarImageService();
    carImageService
      .getCarImages()
      .then((result) => setCarImage(result.data.data));
      
  }, []);

  useEffect(() => {
    let carService = new CarService();
    carService.getCars().then((result) => setCars(result.data.data));
  }, []);

  return (
    <div>
      <Grid columns={3} >
        <Grid.Row>
          {cars.map((car) => (
            <Grid.Column style={{marginBottom:"1em"}}>
              <CarComponent car={car} imagePath={carImages.filter(image=>image.car.id===car.id)[0].imagePath}></CarComponent>
              
            </Grid.Column>
          ))}
        </Grid.Row>
       
      </Grid>
    </div>
  );
}

获取所有汽车图像请求 URL: http://localhost:8080/api/images/getAll

获取所有汽车图像响应正文:

{
  "success": true,
  "message": null,
  "data": [
    {
      "id": 26,
      "imagePath": "http://res.cloudinary.com/dp39jsge0/image/upload/v1629406293/hx80jyfrus88tar0psq4.png",
      "createdAt": "2021-08-19",
      "car": {
        "id": 1,
        "modelYear": 2017,
        "dailyPrice": 600,
        "description": "A6 2.0TDI QUATTRO EDITION",
        "brand": {
          "id": 2,
          "name": "Audi"
        },
        "color": {
          "id": 8,
          "name": "Beyaz"
        },
        "busy": false
      }
    },
    {
      "id": 27,
      "imagePath": "http://res.cloudinary.com/dp39jsge0/image/upload/v1629406541/dynoc7dnjcbns0mv2y1m.png",
      "createdAt": "2021-08-19",
      "car": {
        "id": 2,
        "modelYear": 2018,
        "dailyPrice": 400,
        "description": "ALFA ROMEO GIULIETTA 1.6 JTD PROGRESSİON 120 HP",
        "brand": {
          "id": 1,
          "name": "Alfa Romeo"
        },
        "color": {
          "id": 9,
          "name": "Gri"
        },
        "busy": false
      }
    },
    {
      "id": 28,
      "imagePath": "http://res.cloudinary.com/dp39jsge0/image/upload/v1629406744/fmvdbmqaennil4ptdyoc.png",
      "createdAt": "2021-08-19",
      "car": {
        "id": 3,
        "modelYear": 2018,
        "dailyPrice": 550,
        "description": "BMW 320 DİZEL OTOMATİK-EDITION M SPORT",
        "brand": {
          "id": 3,
          "name": "BMW"
        },
        "color": {
          "id": 10,
          "name": "Kırmızı"
        },
        "busy": false
      }
    },
    {
      "id": 29,
      "imagePath": "http://res.cloudinary.com/dp39jsge0/image/upload/v1629406930/dq4htj3rrdjlbpiqa8iq.png",
      "createdAt": "2021-08-20",
      "car": {
        "id": 4,
        "modelYear": 2016,
        "dailyPrice": 700,
        "description": "C180 COUPE",
        "brand": {
          "id": 10,
          "name": "Mercedes - Benz"
        },
        "color": {
          "id": 11,
          "name": "Lacivert"
        },
        "busy": false
      }
    }
  ]
}

刷新页面几次:sample of list of cars

【问题讨论】:

  • 因为有些车没有照片,所以carImages就是null,不能过滤null?
  • const [carImages, setCarImage] = useState({}); 更改为 const [carImages, setCarImage] = useState([]);
  • 谢谢大家。目前它工作正常。我忘了把初始状态从对象改回数组。
  • 各位,我猜这次imagePath有问题。出现“无法读取未定义的属性‘imagePath’”错误。我是否正确使用 .filter() 方法?我尝试使用以下方法创建 CarComponent:image.car.id===car.id)[0].imagePath}>。那里有一个 [0] 因为只有这样我才能到达纯路径字符串。 carImages.filter(image=>image.car.id===car.id) 的第零个索引是一个实际的 carImage 对象。 (@Dominik,如果应该,您可以将其作为此问题的答案)

标签: javascript reactjs filter


【解决方案1】:

carImages 的初始值必须是数组,而不是对象。

const [carImages, setCarImage] = useState([]);

注意初始值:[],而不是{}

对于第二个错误:

您需要检查filter 的结果,因为当getCars()getCarImages() 之前返回或某些汽车没有任何图像时,filter 返回一个空数组。另外,要摆脱数组,您需要使用find 而不是filter,因为您希望得到一个结果。

export default function CarsList() {


const [cars, setCars] = useState([]);

  const [carImages, setCarImage] = useState([]);

  useEffect(() => {
    let carImageService = new CarImageService();
    carImageService
      .getCarImages()
      .then((result) => setCarImage(result.data.data));
      
  }, []);

  useEffect(() => {
    let carService = new CarService();
    carService.getCars().then((result) => setCars(result.data.data));
  }, []);

  return (
    <div>
      <Grid columns={3} >
        <Grid.Row>
          {cars.map((car) => {
            let image = carImages.find(i=>i.car.id===car.id);
            return 
            <Grid.Column style={{marginBottom:"1em"}}>
              <CarComponent car={car} imagePath={image === undefined ? undefined :image.imagePath}></CarComponent>
              
            </Grid.Column>
          })}
        </Grid.Row>
       
      </Grid>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 2012-04-22
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多