开发者问题收集

未捕获的类型错误:无法读取未定义的属性(读取‘map’)

2022-09-11
228

我正在使用 React 构建这个房地产网站。它第一次运行正常,但每次我重新加载网站时都会出现错误: Uncaught TypeError:无法读取未定义的属性(读取‘map’)

 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: "",
  });

  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))
      .catch((err) => console.error(err));
  }, [filterVal]);


  console.log(propertyData);

  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}
      />
    );
  });
  
}
1个回答

可能 propertyData 在渲染之前是 undefined ,因此它不会映射。您应该使用 ? 添加控制,因此它应该像 hits?.map 一样开始

Evren
2022-09-11