gpt4 book ai didi

reactjs - TS2531 | React useRef - 对象可能未定义

转载 作者:行者123 更新时间:2023-12-02 19:22:15 25 4
gpt4 key购买 nike

我需要在 React 中为我的谷歌地图设置新的纬度和经度
Const mapRef 返回错误:对象可能为“null”。 TS2531
当我使用 let 而不是 React.useRef 时,它可以工作。
我认为应该将类型设置为mapRef,但我不知道是哪一个以及在哪里可以找到它。
但我认为 useRef 是更好的解决方案,不是吗?

Google map 库:https://www.npmjs.com/package/@react-google-maps/api

const libraries = ["places"];

const CustomMap = () => {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: "MY_API_KEY",
libraries,
});

const options = {
disableDefaultUI: true,
zoomControl: true,
};

const mapRef = React.useRef();
const onMapLoad = React.useCallback((map) => {
mapRef.current = map;
}, []);

const panTo = React.useCallback(({ lat, lng }) => {
if (null !== mapRef.current) {
// There is error
// mapRef.current Object is possibly 'null'. TS2531
mapRef.current.panTo({ lat, lng });
mapRef.current.setZoom(18);
}
}, []);
//console.log("maps show coord: ", props.coordinates);

if (loadError) {
return (
<Fragment>
<p>Error</p>
</Fragment>
);
}
if (!isLoaded) {
return (
<Fragment>
<p>loading</p>
</Fragment>
);
}
return (
<div>
<Search panTo={panTo} />
<GoogleMap
id="map"
mapContainerStyle={mapContainerStyle}
zoom={15}
center={center}
//options={options}
onLoad={onMapLoad}
/>
</div>
);
};

最佳答案

使用this package查找类型,然后设置 useRef 的类型并使用 null 对其进行初始化。

const mapRef: Type = React.useRef(null); // Replace `Type` with the actual type from the package

在您的情况下,类型似乎是 google.maps.Map 所以

const mapRef: google.maps.Map = React.useRef(null);

应该可以解决问题。

关于reactjs - TS2531 | React useRef - 对象可能未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62882992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com