React.js中Uncaught Error: Cannot find module './undefined.jpg'错误修复及原因排查
React项目先出现'./undefined.jpg'模块找不到错误,后渲染真实图片路径的原因及解决办法
我遇到一个问题:React项目中会先抛出./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;
问题原因
- 初始状态
useState([{}])是一个包含空对象的数组,组件首次渲染时,car.title为undefined,导致require(../temp-img/${car.title}.jpg)被解析为require('../temp-img/undefined.jpg')。webpack在编译阶段会尝试解析这个不存在的模块,直接抛出错误。 - 后续axios请求完成后虽会更新
carsInfo,但首次渲染触发的错误无法被状态更新修复。
解决办法
方案1:初始状态设为空数组,渲染前判断数组长度
将初始状态改为空数组,在执行map前判断数组是否有内容,避免渲染空对象:
const [carsInfo, setCarsInfo] = useState([]); // ... return ( <div className={style.mainCotainer}> <main className={style.main}> <h1>Cars</h1> <div className={style.container}> {carsInfo.length > 0 ? ( carsInfo.map((car) => ( <Link to={`/cars/${car.name}`} key={car.id}> <div className={style.card} key={car.id}> <h3>{car.name}</h3> <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> )) ) : ( <p>加载中...</p> {/* 可选:添加加载提示 */} )} </div> </main> </div> );
方案2:单个car对象判断,确保title存在再渲染图片
如果需要保留初始数组结构,可在渲染img前判断car.title是否存在:
{carsInfo.map((car) => ( <Link to={`/cars/${car.name}`} key={car.id}> <div className={style.card} key={car.id}> <h3>{car.name}</h3> <p>{car.body_type}</p> <p>{car.origin}</p> <p>{car.year}</p> {car.title && ( <img src={require(`../temp-img/${car.title}.jpg`)} alt={car.name} style={{ width: '200px' }} /> )} </div> </Link> ))}
方案3:直接拼接路径(图片放public目录时适用)
若图片存放在项目的public文件夹下,可不用require,直接拼接路径,避免webpack提前解析不存在的模块:
// 假设图片路径为 public/temp-img/xxx.jpg <img src={`/temp-img/${car.title}.jpg`} alt={car.name} style={{ width: '200px' }} onError={(e) => e.target.style.display = 'none'} {/* 可选:加载失败时隐藏图片 */} />
内容的提问来源于stack exchange,提问作者sammy
相关产品推荐
相关产品推荐

