2017-07-31 68 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>