export class GetLocation extends React.Component{
_geolocation(){
const options = {
enableHighAccuracy: true,
timeout : 8000,
maximumAge: 1000
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setCurrentAdress(position.coords.longitude,position.coords.latitude);
},
(error) => {
const errorTypes={1:"位置服务被拒绝", 2:"获取不到位置信息", 3:"获取位置信息超时"};
this.props.getAddress(errorTypes[error.code])
}
);
}
else {
alert("你的浏览器不支持!");
}
}
setCurrentAdress(lon,lat){
let gc = new BMap.Geocoder();
let point = new BMap.Point(lon,lat)
gc.getLocation(point, (rs) => {
this.props.getAddress(rs.address)
});
}
render(){
return(
<BaiduMap id="getlocation" style={{display:'none'}} />
)
}
}
export default class MobilefieldSignInfo extends React.Component{
constructor(){
super();
this.state = {
address : ''
};
this.getLocation = this.getLocation.bind(this);
this.onAddressChanged = this.onAddressChanged.bind(this);
}
getLocation(){
this.setState({
address : ''
},this.setState({
address : this.refs.location._geolocation()
}))
}
componentDidMount(){
this.getLocation();
}
onAddressChanged(add){
this.setState({
address : add
})
}
render() {
return (
<Container scrollable>
<MobilefieldSign currentLocation={this.state.address} />
<GetLocation ref="location" getAddress={this.onAddressChanged} />
<Button block radius>签 到</Button>
<Button block radius onClick={this.getLocation} theme="white"><Icon name="refresh" />重新定位</Button>
</Container>
);
}
};
调用百度地图获取当前的地理位置,还没获取到地址就退出当前页面,就会报错
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
该怎么卸载呢
我觉的除了验证还可以这么做,在另一个hook函数
componentWillUnmount
中,发一个abort的request取消先前发出的request,这样好像返回的data是undefined,然后当然也不会进行后续操作了。大神轻喷
update:
官网文章,目测有点用,HERE
里面大概意思就是,不鼓励用isMounted(),而是用一个变量来在生命周期中显式的记录组件状态。
还有种更好的解决方法是,把异步操作包裹在一个cancelablePromise中,具体实现文章里面有。