首页 > 解决方案 > 无法在子组件中读取包含对象数组的道具

问题描述

我正在尝试在地图中显示多个标记。

我在父组件中有这段代码:

const [coords, setCoords] = useState ([{}])

setCoords(
         [
           {lat: -5.2119899, lng: 119.4461816},
           {lat: -5.209704, lng: 119.44075},
         ]
       )

<ReactGoogleMaps coordinates={coords} />

子组件中的代码片段:

const WrappedMap = withScriptjs(withGoogleMap((props) =>
<GoogleMap
    defaultZoom={13}
    defaultCenter={{ lat: Number(props.coordinates.lat), lng: Number(props.coordinates.lng) }}
  >
    {props.isMarkerShown && <Marker position={{ lat: Number(props.coordinates.lat), lng: Number(props.coordinates.lng)}} />}
  </GoogleMap>
));

function ReactGoogleMaps(props) {
    return (
        <div style={{width: "100%", height: "100%"}}>
            <WrappedMap 
                coordinates={{lat: props.coordinates[0].lat, lng: props.coordinates[0].lng}}
            />
        </div>
    )
};

上面的代码运行良好。问题是当坐标道具的索引从0更改为1时,它会返回此错误:TypeError: Cannot read property 'lat' of undefined

我已经坚持了几天了。如果有人可以帮助我,我将不胜感激。非常感谢你。

标签: javascriptreactjs

解决方案


当第一次渲染发生时,不会立即设置坐标ReactGoogleMaps。因此,当您尝试访问 props.coordinates[0] 的纬度时,您会收到此未定义的错误。

我建议:

  • 在 coords.length > 0 之前不渲染 ReactGoogleMaps
  • 在尝试访问之前检查第一个元素的存在,如下所示:
    function ReactGoogleMaps(props) {
        return (
            <div style={{width: "100%", height: "100%"}}>
                { props.coordinates[0] &&
                    <WrappedMap 
                        coordinates={{lat: props.coordinates[0].lat, lng: props.coordinates[0].lng}}
                    />
                }
            </div>
        )
    };

推荐阅读