为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喔喔 2022-12-22 14:41:44
我正在尝试在地图中显示多个标记。我在父组件中有这段代码: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。我已经坚持了几天。如果有人可以帮助我,我将非常感激。提前非常感谢你。
查看完整描述

2 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

第一次渲染发生时,不会立即设置坐标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>

        )

    };


查看完整回答
反对 回复 2022-12-22
?
达令说

TA贡献1821条经验 获得超6个赞

孩子甚至得到更新的道具吗?IMO,在您使用 setCoords 之后,道具不会在孩子中更新。


第一个解决方案使用您正在使用的默认值进行初始化:


 const [coords, setCoords] = useState ([

              {lat: -5.2119899, lng: 119.4461816},

           {lat: -5.209704, lng: 119.44075},

])

第二种解决方案,试试 UseEffect():


function ReactGoogleMaps(props) {

    const [coords, setCords] = useState (props.coordinates)

      useEffect(() => {

         setCords(props.coordinates);

     }, [props]);


    return (

        <div style={{width: "100%", height: "100%"}}>

            <WrappedMap 

                coordinates={{lat: coords[0].lat, lng: coords[0].lng}}

            />

        </div>

    )

};

注意:我还没有测试过,但希望它能工作


查看完整回答
反对 回复 2022-12-22
  • 2 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号