开发者问题收集

React JS:TypeError:无法将未定义或空转换为对象

2020-11-25
3843

我这里有一个 Beach 组件,它向我抛出了错误:

TypeError: Cannot convert undefined or null to object
ResortDetail
C:/Users/JS/Desktop/MERN/KR/frontend/src/screens/Beach.js:33
  30 |           <p>{description}</p>
  31 |           <br/>
  32 |           <h4>Amenities:</h4>
> 33 | <div>
     | ^  34 | { 
  35 |                 Object.entries(amenities).map(
  36 |                   ([key, value]) => {
View compiled
▶ 17 stack frames were collapsed.

基本上,数据看起来像这样:

{_id: "2", name: "Bluewater Maribago Beach Resort", price_per_night: 4156,…}
address: "Buyong"
amenities: {tv: true, reservation: true}
city: "New York"
description: "Set in a complex of thatch-roofed buildings on the Cebu Strait, this posh beachfront resort is 1 km from Mactan Island Aquarium and 4 km from the Magellan Shrine."
email: "[email protected]"
image: "https://images.unsplash.com/photo-1507525428034-b723cf961d3e"
latitude: 10.290899
longitude: 124.000822
name: "Bluewater Maribago Beach Resort"
phone: "(032) 402 4100"
price_per_night: 4156
province: "California Road"
rating: 3.5
reviews: 35
website: "http://www.bluewater.us/"
zip_code: "6015"
_id: "2"

我认为它抱怨 Object.entries(amenities).map( 但不确定为什么以及如何修复它。

这是完整的代码:

import React, { useState, useEffect } from 'react'
import axios from 'axios'

const Beach = ({ match }) => {
     
     const [resort, setResort] = useState({})

     useEffect(() => {
        const fetchBeach = async () => {
            const { data } = await axios.get(`/api/resorts/${match.params.id}`)
            setResort(data)
        }
 
        fetchBeach()
     }, [match])
    
    const { name, address, city, province, zip_code, image, description, amenities, website, phone, email } = resort

    return (
        <div className="row mt-5">
            <div className="col-lg-7">
            <h1>{name}</h1>
            <p><FaMapMarkerAlt /> {`${address}, ${city} ${province}, USA, ${zip_code}`}</p>
            <img src={image} alt={name} width="700" />
            <br/>
            <p>{description}</p>
            <br/>
            <h4>Amenities:</h4>
  <div>
  { 
                  Object.entries(amenities).map(
                    ([key, value]) => {
                        if(value){
                            return <p>{key}</p>
                        }
                       return null
                    }
                )
               }
            </div> 
        </div>



        </div>
    ) 
}

export default Beach

有什么想法如何修复这个问题并正确地拉起对象设施?

2个回答

“amenities”一开始是未定义的,因为从 API 获取数据需要一些时间。所以您的代码最终为 Object.entries(null),因此出现错误。 在使用 Object.entires() 之前,请检查 amenities 是否不为 null,如下所示。

amenities && Object.entries(amenities).map(
                    ([key, value]) => {
                        if(value){
                            return <p>{key}</p>
                        }
                       return null
                    }
                )
               }

希望有帮助!:))

Sonish Maharjan
2020-11-25
import React, { useState, useEffect } from "react";
import axios from "axios";

const Beach = ({ match }) => {
  const [resort, setResort] = useState(null);

  useEffect(() => {
    const fetchBeach = async () => {
      const { data } = await axios.get(`/api/resorts/${match.params.id}`);
      setResort(data);
    };

    fetchBeach();
  }, [match]);

  const {
    name,
    address,
    city,
    province,
    zip_code,
    image,
    description,
    amenities,
    website,
    phone,
    email,
  } = resort;

  return (
    <div className="row mt-5">
      <div className="col-lg-7">
        <h1>{name}</h1>
        <p>
          <FaMapMarkerAlt />{" "}
          {`${address}, ${city} ${province}, USA, ${zip_code}`}
        </p>
        <img src={image} alt={name} width="700" />
        <br />
        <p>{description}</p>
        <br />
        <h4>Amenities:</h4>
        <div>
          {resort
            ? Object.entries(amenities).map(([key, value]) => {
                if (value) {
                  return <p>{key}</p>;
                }
                return null;
              })
            : null}
        </div>
      </div>
    </div>
  );
};

export default Beach;
Ketan Ramteke
2020-11-25