mongodb 如何修复(未捕获的错误:在React.js中找不到模块'./undefined.jp')

cqoc49vn  于 2023-02-11  发布在  Go
关注(0)|答案(1)|浏览(91)

我很想知道为什么它在其他任何东西之前给出这个“。/undefined. jpg”,只有在那之后,才呈现所有的实际路径。

import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import style from './CarsListPage.module.scss';
//import cars from './car-content';
import CarsList from '../components/CarsList';

const CarsListPage = () => {
  const [carsInfo, setCarsInfo] = useState([{}]);

  useEffect(() => {
    const loadCarsInfo = async () => {
      const response = await axios.get('/api/cars');
      const newCarsInfo = response.data;
      setCarsInfo(newCarsInfo);
    };
    loadCarsInfo();
  }, []);

  return (
    <div className={style.mainCotainer}>
      <main className={style.main}>
        <h1>Cars</h1>
        <div className={style.container}>
          {carsInfo.map((car) => (
            <Link to={`/cars/${car.name}`} key={car.id}>
              <div className={style.card} key={car.id}>
                <h3>{car.name}</h3>
                {/* {console.log(`../temp-img/${car.title}.jpg`)} */}
                <p>{car.body_type}</p>
                <p>{car.origin}</p>
                <p>{car.year}</p>
                <img
                  src={require(`../temp-img/${car.title}.jpg`)}
                  alt={car.name}
                  style={{ width: '200px' }}
                />
              </div>
            </Link>
          ))}
        </div>
      </main>
    </div>
  );
};

export default CarsListPage;

我已经找到了一些解决方案,比如把所有东西都 Package 成div,然后检查值是否存在,但是我不能为我的代码优化它。

yshpjwxd

yshpjwxd1#

carsInfo的默认状态更改为[],否则将Map到空对象,直到从API获取数据:

const CarsListPage = () => {
  const [carsInfo, setCarsInfo] = useState([]);

  useEffect(() => {
    const loadCarsInfo = async () => {
      const response = await axios.get('/api/cars');
      const newCarsInfo = response.data;
      setCarsInfo(newCarsInfo);
    };
    loadCarsInfo();
  }, []);

  return (
    <div className={style.mainCotainer}>
      <main className={style.main}>
        <h1>Cars</h1>
        <div className={style.container}>
          {carsInfo.length && carsInfo.map((car) => (
            <Link to={`/cars/${car.name}`} key={car.id}>
              <div className={style.card} key={car.id}>
                <h3>{car.name}</h3>
                {/* {console.log(`../temp-img/${car.title}.jpg`)} */}
                <p>{car.body_type}</p>
                <p>{car.origin}</p>
                <p>{car.year}</p>
                <img
                  src={require(`../temp-img/${car.title}.jpg`)}
                  alt={car.name}
                  style={{ width: '200px' }}
                />
              </div>
            </Link>
          ))}
        </div>
      </main>
    </div>
  );
};

相关问题