簡體   English   中英

Map 通過對象數組並將道具傳遞給特定組件

[英]Map through array of objects and pass props to specific component

這是我的數組:

const locations = [
    {
      results: [
        {
          name: "Rome, Italy",
          price: 100,
          distance: 1299,
          match: 96,
          lat: 40,
          lng: 60,
        },
        {
          name: "Beijing, China",
          price: 200,
          distance: 3000,
          match: 93,
          lat: 100,
          lng: 100,
        },
        {
          name: "California, USA",
          price: 250,
          distance: 420,
          match: 75,
          lat: 200,
          lng: 200,
        },
      ],
    },
    {
      results: [
        {
          name: "Rome, Italy",
          price: 100,
          distance: 1299,
          match: 96,
          lat: 50,
          lng: 60,
        },
        {
          name: "Beijing, China",
          price: 200,
          distance: 3000,
          match: 93,
          lat: 100,
          lng: 100,
        },
        {
          name: "California, USA",
          price: 250,
          distance: 420,
          match: 75,
          lat: 200,
          lng: 200,
        },
      ],
    },
  ];

現在,我想獲取latlng坐標並將它們作為道具傳遞給這個組件:

 {locations.map((location, index) => {
              return <MapMarker locations={locations[index]} />;
            })}

這是實際的組件代碼:

<MapMarkerContainersContainer>
      {locations.map((location, index) => {
        return (
          <AnyReactComponent
            lat={location.result[index].lat}
            lng={location.result[index].lng}
            text="My Marker"
          />
        );
      })}
    </MapMarkerContainersContainer>

知道我做錯了什么嗎?

您正在使用locations數組的索引。 因此,您可以減少locations數組中的所有locations.result ,而不是使用location.result[index]並循環結果:

<MapMarkerContainersContainer>
{
  locations
    .reduce((acc, cur) => [...acc, ...cur.results], [])
    .map((location) => {
      return (
        <AnyReactComponent
          lat={location.lat}
          lng={location.lng}
          text="My Marker"
        />
      );
    })
}
</MapMarkerContainersContainer>

你有數組里面的數組,所以你可以先把它們弄平。

  const marks = []
  locations.forEach(v => {
    v.results.forEach(i => { mark.push(i) })
  })

接着

      {marks.map(m => 
          <AnyReactComponent
            key={`${m.lat}${m.lng}`}
            lat={m.lat}
            lng={m.lng}
            text="My Marker"
          />
      })}

您需要密鑰,否則會出錯。

您需要在調用 map 之前展平陣列。

<MapMarkerContainersContainer>
    {locations.reduce((prev, cur) => [...prev, ...cur.results], []).map((location, index) => {
        return (
            <AnyReactComponent
                lat={location.lat}
                lng={location.lng}
                text="My Marker"
            />
        );
    })}
</MapMarkerContainersContainer>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM