开发者社区> 问答> 正文

react 组件卸载的问题

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.
该怎么卸载呢

展开
收起
a123456678 2016-03-11 10:02:41 4597 0
1 条回答
写回答
取消 提交回答
  • Just set a _isMounted property to true in componentDidMount and set it to false in componentWillUnmount, and use this variable to check your component's status.
    2019-07-17 18:58:28
    赞同 展开评论 打赏
问答标签:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React在大型后台管理项目中的工程实践 立即下载