使用Props结合Map函数时出现Undefined报错,如何解决?
问题:Mapbox集成时无法读取API数据,出现undefined报错
在开发教程页面集成Mapbox时,调用返回住宿列表的API后,未成功获取对象值,反而出现undefined,触发以下错误:
Server Error
TypeError: Cannot read properties of undefined (reading 'map')

期望获取的API返回数据格式如下:
相关代码
AirBnbMap.js (组件)
import { useState } from "react"; import Map from "react-map-gl"; import { getCenter } from "geolib"; function AirBnbMap({ searchResults }) { // 将搜索结果转换为经纬度对象格式 const coordinates = searchResults.map((result) => ({ longitude: result.long, latitude: result.lat, })); console.log(coordinates); // 计算所有坐标的中心点 const center = getCenter(coordinates); const [viewState, setViewState] = useState({ longitude: center.longitude, latitude: center.latitude, zoom: 3.5, }); return ( <Map {...viewState} onMove={(evt) => setViewState(evt.viewState)} style={{ width: "100%", height: "100%" }} mapStyle="mapbox://styles/mapbox/streets-v9" mapboxAccessToken={process.env.mapbox_key} /> ); } export default AirBnbMap;
search.js (页面)
import { useRouter } from "next/router"; import { format } from "date-fns"; import Header from "../components/Header"; import Footer from "../components/Footer"; import InfoCard from "../components/InfoCard"; import AirBnbMap from "../components/AirBnbMap"; function Search({ searchResults }) { const router = useRouter(); // ES6解构获取路由参数 const { location, startDate, endDate, noOfGuests } = router.query; const formattedStartDate = format(new Date(startDate), "dd MMMM yy"); const formattedEndDate = format(new Date(endDate), "dd MMMM yy"); const range = `${formattedStartDate} - ${formattedEndDate}`; return ( <div> <Header placeholder={`${location} | ${range} | ${noOfGuests} guests`} /> <main className="flex "> <section className="flex-grow pt-14 px-6"> <p className="text-xs"> 300+ Stays - {range} - for {noOfGuests} guests </p> <h1 className="text-3xl font-semibold mt-2 mb-6"> Stays in {location} </h1> <div className="hidden lg:inline-flex mb-5 space-x-3 text-gray-800 whitespace-nowrap"> <p className="button">Cancellation Flexibility</p> <p className="button">Type of Place</p> <p className="button">Price</p> <p className="button">Rooms and Beds</p> <p className="button">More filters</p> </div> <div className="flex flex-col"> {searchResults?.map( ({ img, location, title, description, star, price, total }) => ( <InfoCard key={img} img={img} location={location} title={title} description={description} star={star} price={price} total={total} /> ) )} </div> </section> <section className="hidden xl:inline-flex xl:min-w-[40%] sticky top-[76px] h-[calc(100vh-76px)]"> <AirBnbMap /> </section> </main> <Footer /> </div> ); } export default Search; export async function getServerSideProps() { const searchResults = await fetch("https://www.jsonkeeper.com/b/5NPS").then( (res) => res.json() ); return { props: { searchResults, }, }; }
解决方案
1. 修复组件属性传递问题
在search.js中,你没有给<AirBnbMap />传递searchResults属性,导致组件内的searchResults为undefined,调用map方法时报错。修改代码:
// search.js中对应的AirBnbMap调用部分 <AirBnbMap searchResults={searchResults} />
2. 添加空值安全处理
即使传递了属性,也需考虑API请求失败或数据为空的情况,给searchResults添加可选链操作,并设置默认空数组:
// AirBnbMap.js中转换坐标的部分 const coordinates = searchResults?.map((result) => ({ longitude: result.long, latitude: result.lat, })) || [];
3. 处理中心点计算的边界情况
当coordinates为空数组时,getCenter会报错,需提前判断:
// AirBnbMap.js中计算中心点的部分 const center = coordinates.length > 0 ? getCenter(coordinates) : { longitude: 0, latitude: 0 };
内容的提问来源于stack exchange,提问作者Sameer M
相关产品推荐
相关产品推荐

