2017-07-31 66 views
0

我有以下行为者:地理位置 - 不能得到经纬度反应,和/终极版应用

export const getLocation =() => { 
    const geolocation = navigator.geolocation; 

    const location = new Promise((resolve, reject) => { 
     if (!geolocation) { 
      reject(new Error('Not Supported')); 
     } 

    geolocation.getCurrentPosition((position) => { 
     resolve(position); 
    },() => { 
     reject (new Error('Permission denied')); 
    }); 
    }); 

    return { 
     type: GET_LOCATION, 
     payload: location 
    } 
}; 

而对于GET_LOCATION型以下减速器:

case GET_LOCATION: { 
      return { 
       ...state, 
       location: { 
        latitude: action.location.coords.latitude, 
        longitude: action.location.coords.latitude, 

       } 
      } 
     } 

我尝试使用这个数据在我的组件像这样:

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import { getLocation } from '../actions'; 
import { bindActionCreators } from 'redux'; 

class UserLocation extends Component { 
    constructor(props) { 
     super(props); 
    } 

    componentWillMount() { 
     this.props.getLocation(); 
    } 

    render() { 
     return (
      <div> 
       <div><span>latitude:</span>{this.props.location.latitude} 
      </div> 
      <div><span>longitude:</span>{this.props.location.longitude} </div> 
     </div> 
    ); 
    } 
} 

const mapDispatchToProps = dispatch => { 
    return bindActionCreators({ getLocation }, dispatch) 
} 

export default connect(null, mapDispatchToProps)(UserLocation); 

但是每当我加载这个组件我得到TypeError: Cannot read property 'latitude' of undefined

你能指点我哪里错了吗?

回答

0

地理定位数据将被异步解析,并且在第一次渲染组件时不可用。您需要正确处理数据尚不可用的情况,并且您可以通过多种方式来实现。有关如何处理不可用数据的说明,请参阅文章Watch Out for Undefined State

0

您应该使用componentWillReceiveProps接收从派发操作返回的数据。

componentWillReceiveProps = (nextProps) => { 
    if (this.props.location.latitude !== nextProps.location.latitude) { 
     // You will have location object here that is returned from recuder 
    } 
    } 

检查这种替代方法来调用地理编码获取经纬度和长期与终极版

https://medium.com/@eesh.t/auto-detect-location-react-component-using-google-geocoding-and-reverse-geocoding-in-autocomplete-66a269c59315

0

你在做componentWillMount()的要求,它的前安装成分反应,但这并不意味着组件将等待请求结束。因此,您应该在呈现方法中进行一些验证,如if(!this.props.location) return <div>Loading...</div>