reactjs - 在 ReactJS 中集成 Mapbox 的错误
问题描述
本质上,我想执行以下操作\
1. As soon as the webpage loads, Get the current coordinates of the user using geoLocation API
2. Then initialize the map in mapbox with center as the users current co-ordinates.
我的代码如下
class MapContainer extends React.Component {
constructor(props) {
super(props);
// Initializing the lat , lng and map to NULL in the state
this.state = { lat: null , lng: null , zoom: 15, map : null};
this.mapContainer = React.createRef();
}
mapInit = ()=>{
const map = new mapboxgl.Map({
container: this.mapContainer.current,
style: 'mapbox://styles/mapbox/streets-v11',
center: [this.state.lng, this.state.lat],
zoom: this.state.zoom
});
this.setState({map : map});
}
getCurrCoords = ()=>{
console.log("hello world");
window.navigator.geolocation.getCurrentPosition(
(position)=> {
this.setState({lat : position.coords.latitude , lng : position.coords.longitude});
this.mapInit();
return;
},
(err) => { console.log(err); }
);
}
componentDidMount = async ()=>{
// Get the users current Location
await this.getCurrCoords();
await this.mapInit();
this.state.map.on('move', () => {
this.setState({
lng: this.state.map.getCenter().lng,
lat: this.state.map.getCenter().lat,
zoom: this.state.map.getZoom().toFixed(2)
});
});
}
render() {
return (
// this is the reference being created. And we can do DOM manipulation to this component
<>
<div className="sidebar">
Longitude: {this.state.lng} | Latitude: {this.state.lat} | Zoom: {this.state.zoom}
</div>
<div ref={this.mapContainer} className='map-container'></div>
</>
)
}
}
由于 componentDidMount 是一个异步函数
所以首先它应该等待 getCurrCoords 完成更新状态中的 lat 和 lng
之后它应该调用 mapInit 函数并等待它完成它的工作。
这意味着 componentDidMount() 没有等待 getCurrCoords 函数。我对吗?还是有一些我还不知道的更深层次的问题。
将 ComponentDidMount() 作为异步函数和地理定位 API 是否可以在等待下工作?
解决方案
推荐阅读
- java - 将单个流拆分为两个列表
- visual-studio-extensions - 可以通过扩展以编程方式重命名“链接”文件吗
- amazon-web-services - 在 AWS Lambdas 中调用 API 是一种好习惯吗?
- javascript - 求矩形面积和周长的独立函数第二部分
- typescript - Typescript 中对象文字的更严格返回类型
- c# - Discord.NET '对象引用未设置为对象的实例。C#
- swift - Swift - PKPushRegistry / VOIP 令牌不改变
- sql - 递归加入最近的祖先/父母以在同一个表中记录?
- google-sheets - Google Sheet:如何使用 arrayformula 将数据从一张表复制到另一张表?
- speech-to-text - 比较段落