猿问

包含对象数组的道具无法在子组件中读取

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


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


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。


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


喵喔喔
浏览 104回答 2
2回答

蓝山帝景

第一次渲染发生时,不会立即设置坐标ReactGoogleMaps。因此,当您尝试访问 props.coordinates[0] 的纬度时,您会收到此未定义的错误。我建议:在 coords.length > 0 之前不渲染 ReactGoogleMaps在尝试访问之前检查第一个元素是否存在,如下所示:&nbsp; &nbsp; function ReactGoogleMaps(props) {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div style={{width: "100%", height: "100%"}}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { props.coordinates[0] &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <WrappedMap&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; coordinates={{lat: props.coordinates[0].lat, lng: props.coordinates[0].lng}}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; };

达令说

孩子甚至得到更新的道具吗?IMO,在您使用 setCoords 之后,道具不会在孩子中更新。第一个解决方案使用您正在使用的默认值进行初始化:&nbsp;const [coords, setCoords] = useState ([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {lat: -5.2119899, lng: 119.4461816},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{lat: -5.209704, lng: 119.44075},])第二种解决方案,试试 UseEffect():function ReactGoogleMaps(props) {&nbsp; &nbsp; const [coords, setCords] = useState (props.coordinates)&nbsp; &nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;setCords(props.coordinates);&nbsp; &nbsp; &nbsp;}, [props]);&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div style={{width: "100%", height: "100%"}}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <WrappedMap&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; coordinates={{lat: coords[0].lat, lng: coords[0].lng}}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )};注意:我还没有测试过,但希望它能工作
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答