为什么这个函数会显示两次 ReactJS?

Why does this function display twice ReactJS?

我的输入是

{
    "location": {
        "name": "name1",
        "address": "addres1",
        "phone": "637636***",
        "facility": "facility1",
        "lat": //this is lattitude, 
        "lng": //this is longitude
    }, 
    "distance": 859.2556649163248
}

处理过程如下:

    function Turup() {
     return Object.entries(nearbyPlace).map(([key, value], i) => {
          return (
               <div>
                    <ul key={key}>
                         <li className='font-bold'>name :</li>
                         <li>address : </li>
                         <li>phone : </li>
                         <li>facility : </li>
                         <li>latitude : </li>
                         <li>longitude : </li>
                    </ul>
               </div>
          )
     })
}

这个功能组件return两次结果,但一次有值,一次有空值

问题是您有一个对象,您试图将它当作一个数组来循环。由于该对象在第一层有两个成员,即 locationdistance,因此您会进行两次迭代。 Proof-of-concept:

var nearbyPlace = [{
    location: {
        name: "name1",
        address: "addres1",
        phone: "637636***",
        facility: "facility1",
        lat: 123, 
        lng: 456
    }, 
    distance: 859.2556649163248
}]

    function Turup() {
     return Object.entries(nearbyPlace).map(([key, value], i) => {
          return (
               `<div>
                    <ul key=${key}>
                         <li className='font-bold'>name :</li>
                         <li>address : ${value.location.address}</li>
                         <li>phone : ${value.location.phone}</li>
                         <li>facility : ${value.location.facility}</li>
                         <li>latitude : ${value.location.lat}</li>
                         <li>longitude : ${value.location.lng}</li>
                    </ul>
               </div>`
          )
     })
}

let turup = Turup();
console.log({length: turup.length, content:turup});

快速解决

    function Turup() {
     return Object.entries([nearbyPlace]).map(([key, value], i) => {
          return (
               <div>
                    <ul key={key}>
                         <li className='font-bold'>name :</li>
                         <li>address : </li>
                         <li>phone : </li>
                         <li>facility : </li>
                         <li>latitude : </li>
                         <li>longitude : </li>
                    </ul>
               </div>
          )
     })
    }

请注意 nearbyPlace 周围的 [],它们会将您的输入转换为 1 元素数组。如果你总是有一个元素,那么在 entries 上做一个循环是不必要的和多余的,但你必须决定是否需要一个循环。