React房产网站刷新报错:Uncaught TypeError: Cannot read properties of undefined (reading 'map')
React页面刷新时出现
Uncaught TypeError: Cannot read properties of undefined (reading 'map')的解决方法 问题根源
你遇到的错误是因为组件初始化时,propertyData的初始值是空对象{}。页面刷新后组件重新渲染,此时fetch请求还未完成,propertyData里的hits属性处于undefined状态,直接调用hits.map()就会触发类型错误。首次运行正常是因为组件挂载后fetch请求已完成,hits被赋值为数组,能正常执行映射。
解决方案
方案一:初始化时给propertyData设置默认hits空数组
修改useState的初始值,让hits默认是一个空数组,这样即使请求未返回,调用map()也不会报错:
const [propertyData, setPropertyData] = React.useState({ hits: [] });
方案二:用可选链+空值合并安全访问hits
在解构和映射时添加安全判断,确保hits存在或有默认值:
const { hits = [] } = propertyData; const propertyCard = hits.map((prop) => { return ( <Property coverPhoto={prop.coverPhoto} price={prop.price} rentFrequency={prop.rentFrequency} rooms={prop.rooms} title={prop.title} baths={prop.baths} area={prop.area} agency={prop.agency} isVerified={prop.isVerified} externalID={prop.externalID} key={prop.id} /> ); });
或者直接在map前用可选链判断:
const propertyCard = hits?.map((prop) => { // 原组件代码 });
方案三:添加加载状态,请求完成前不渲染列表
新增加载状态变量,在请求未完成时显示加载提示,避免渲染未准备好的数据:
export default function App() { const [propertyData, setPropertyData] = React.useState({}); const [searchFilters, setSearchFilters] = React.useState(false); const [filterVal, setFilterVal] = React.useState({ rentFrequency: "", minPrice: "", maxPrice: "", areaMax: "", roomsMin: "", bathsMin: "", }); const [isLoading, setIsLoading] = React.useState(true); // 新增加载状态 React.useEffect(() => { const options = { method: "GET", headers: { "X-RapidAPI-Key": "", "X-RapidAPI-Host": "bayut.p.rapidapi.com", }, }; fetch( `https://bayut.p.rapidapi.com/properties/list?locationExternalIDs=5002%2C6020&purpose=for-rent&hitsPerPage=9&lang=en&rentFrequency=${filterVal.rentFrequency}&priceMin=${filterVal.minPrice}&priceMax=${filterVal.maxPrice}&areaMax=${filterVal.areaMax}&roomsMin=${filterVal.roomsMin}&bathsMin=${filterVal.bathsMin}`, options ) .then((response) => response.json()) .then((data) => { setPropertyData(data); setIsLoading(false); // 请求完成关闭加载 }) .catch((err) => { console.error(err); setIsLoading(false); // 请求失败也关闭加载 }); }, [filterVal]); // 加载中时显示提示 if (isLoading) { return <div>加载中...</div>; } const { hits = [] } = propertyData; const propertyCard = hits.map((prop) => { return ( <Property coverPhoto={prop.coverPhoto} price={prop.price} rentFrequency={prop.rentFrequency} rooms={prop.rooms} title={prop.title} baths={prop.baths} area={prop.area} agency={prop.agency} isVerified={prop.isVerified} externalID={prop.externalID} key={prop.id} /> ); }); // 后续渲染逻辑 }
内容的提问来源于stack exchange,提问作者Devansh Kariya
相关产品推荐
相关产品推荐

