如何使用 map() 为数组中的每个元素 return 多个组件?

How to return multiple components for each element in a array using map()?

我试过这样做。 我想 return 多个 <LocationMarker> 每个“ev”。但是每个“ev”只有 returning 一个 <LocationMarker>。 storm 变量内的 for 循环只执行一次。 我还尝试在 return 函数中保留 for 循环,但出现错误。

提前致谢

import { useState } from 'react';
import GoogleMapReact from 'google-map-react';
import LocationMarker from './LocationMarker';
import LocationInfoBox from './LocationInfoBox';
const NATURAL_EVENT_SEVERESTORMS = 'severeStorms';
const Map = ({ eventData, center, zoom }) => {
const [locationInfo, setLocationInfo] = useState(null);
const storms = eventData.map((ev) => {
    if (ev.categories[0].id === NATURAL_EVENT_SEVERESTORMS) {
      for (let i = 0; i < ev.geometry.length; i++) {
        return (
          <LocationMarker
            lat={ev.geometry[i].coordinates[1]}
            lng={ev.geometry[i].coordinates[0]}
            type='severeStorms'
            onClick={() => setLocationInfo({ id: ev.id, title: ev.title })}
          />
        );
      }
    }
    return null;
  });

  return (
    <div className='map'>
      <GoogleMapReact
        bootstrapURLKeys={{  }}
        defaultCenter={center}
        defaultZoom={zoom}
      >
        {storms}
      </GoogleMapReact>

      {locationInfo && <LocationInfoBox info={locationInfo} />}
    </div>
  );
};

Map.defaultProps = {
  center: {
    lat: 42.3265,
    lng: -122.8756,
  },
  zoom: 4,
};

export default Map;


您将在 for 循环的第一次迭代中返回 LocationMarker JSX。取而代之的是,您应该再次使用 map 方法。

const storms = eventData.map((ev) => {
  if (ev.categories[0].id === NATURAL_EVENT_SEVERESTORMS) {
    return ev.geometry.map((geo) => {
      return (
        <LocationMarker
          lat={geo.coordinates[1]}
          lng={geo.coordinates[0]}
          type='severeStorms'
          onClick={() => setLocationInfo({ id: ev.id, title: ev.title })}
        />
      );
    });
  }
  return null;
});

另请注意,在迭代呈现 JSX 列表时必须添加 'key' 属性。

const storms = eventData.map((ev) => {
  if (ev.categories[0].id === NATURAL_EVENT_SEVERESTORMS) {
    return ev.geometry.map((geo) => {
      return (
        <LocationMarker
          key={CHOOSE_UNIQUE_KEY_FOR_THIS_ITEM}
          lat={geo.coordinates[1]}
          lng={geo.coordinates[0]}
          type='severeStorms'
          onClick={() => setLocationInfo({ id: ev.id, title: ev.title })}
        />
      );
    });
  }
  return null;
});

您可以在此处阅读更多相关信息: https://reactjs.org/docs/lists-and-keys.html

那里有两个嵌套循环,所以为了获得实际的数组,您需要连接每个循环记录,或者只使用 reduce。 这样的事情应该有效:

import { useState } from 'react';
import GoogleMapReact from 'google-map-react';
import LocationMarker from './LocationMarker';
import LocationInfoBox from './LocationInfoBox';
const NATURAL_EVENT_SEVERESTORMS = 'severeStorms';
const Map = ({ eventData, center, zoom }) => {
const [locationInfo, setLocationInfo] = useState(null);
const storms = eventData.reduce((acc, ev, indx) => {
  const geometries = ev.geometry.map((geo, geoIndx) => (
      <LocationMarker
        key={`${indx}-${geoIndx}`}
        lat={geo.coordinates[1]}
        lng={geo.coordinates[0]}
        type='severeStorms'
        onClick={() => setLocationInfo({ id: ev.id, title: ev.title })}
      />
  )
  // Concatenate previously collected records with this iteration map output
  acc = acc.concat(geometries)
  return acc
}, [])


  return (
    <div className='map'>
      <GoogleMapReact
        bootstrapURLKeys={{  }}
        defaultCenter={center}
        defaultZoom={zoom}
      >
        {storms}
      </GoogleMapReact>

      {locationInfo && <LocationInfoBox info={locationInfo} />}
    </div>
  );
};

Map.defaultProps = {
  center: {
    lat: 42.3265,
    lng: -122.8756,
  },
  zoom: 4,
};

export default Map;

您必须将所有 LocationMarker 添加到一个数组中,然后 return 数组,

你现在正在做的是遍历循环,然后在第一个索引 (i=0) 上,return

<LocationMarker
        lat={ev.geometry[i].coordinates[1]}
        lng={ev.geometry[i].coordinates[0]}
        type='severeStorms'
        onClick={() => setLocationInfo({ id: ev.id, title: ev.title })}
      />

来自风暴函数。