2016-07-08 103 views
0

我無法讓數據通過第72行(我標記爲中斷線)。到目前爲止,一切都變好了(數據庫中的數據傳遞給「google-geocoder」,並且「geoPlace」對象通過「數據」參數中的回調傳遞,但是當我嘗試訪問「geocoder」函數外的「數據」數據「變得不明確 我試過.bind,setState,窗口等等,都沒有運氣。 我覺得這是一個範圍問題,但不能確定 任何幫助都會非常感謝,謝謝在ReactJS中獲取API回調函數以外的函數

// Feed 
//  Tools 
//  Listing 
//  Location 
//   FeedMap 
//   MapLoader 

import React from 'react'; 
import geocoder from 'google-geocoder'; 
import FeedMap from './feedMap.js'; 

var Location = React.createClass({ 
    getInitialState: function(){ 
    return { 
     petTrip: [] 
    } 
    }, 

    getAllpetTripFromServer: function(){ 
    var self = this; 
    $.ajax({ 
     method: 'GET', 
     url: '/travel' 
    }).done(function(data){ 
     console.log(data, "I am the data from line 17"); 
     self.setState({ petTrip: data }) 
    }) 
    }, 

    componentDidMount: function(){ 
    this.getAllpetTripFromServer(); 
    }, 

//() 
    render: function(){ 
    console.log(this.state.petTrip, 'I am the console log from line  28'); 
    return (
     <div> 
      <AllpetTrip petTrip={this.state.petTrip}/> 
     </div> 
    ) 
    } 

}); 


var AllpetTrip = React.createClass({ 
    render: function(){ 
     // console.log(this.props.petTrip, "at map") 
    var trips = this.props.petTrip.map(function(item){ 
     return <Geolocator start={item.startPoint}/> 
    }); 

    return (
     <div> 
     { trips } 
     </div> 
    ) 
    } 
}); 




var Geolocator = React.createClass({ 
    render: function(){ 
    var geo = geocoder ({ 
    key: 'AIzaSyC9Zst0uBpxGJ2P4LLv3IMATpN9Ppl4ImI' 
     }); 
     geo.find(this.props.start, function(err, data){ 
     console.log(data, "this is the GeoPlace object") 
     }); 

 return(
     <div> 
     <FeedMap geolocations = { data }/> 
     </div> 
    ) 
    } 

}); 


module.exports = Location; 

回答

0

這是因爲你試圖訪問組件的性能得到這些之前。

var AllpetTrip = React.createClass({ 
    componentWillReceiveProps(props){ 
    this.setState({ 
    petTrip: props.petTrip 
    }) 
    }, 
    getInitialState(){ 
    return({ 
    petTrip: [] 
    }) 
    }, 
    render: function(){ 
     // console.log(this.props.petTrip, "at map") 
    var trips = this.state.petTrip.map(function(item){ 
     return <Geolocator start={item.startPoint}/> 
    }); 

    return (
     <div> 
     { trips } 
     </div> 
    ) 
    } 
}); 

或使用你的代碼的條件:

var AllpetTrip = React.createClass({ 
    render: function(){ 
     // console.log(this.props.petTrip, "at map") 
    var trips = this.props.petTrip.length ? this.props.petTrip.map(function(item){ 
     return <Geolocator start={item.startPoint}/> 
    }) : null 

    return (
     <div> 
     { trips } 
     </div> 
    ) 
    } 
}); 

我希望這有助於。

+0

感謝您抽出時間仔細查看。這不是我遇到問題的地方,AllpetTrip傳遞的數據正確。在「Geolocator」組件中,我無法將數據傳遞給我的React Map。地理編碼器函數可以工作,並在回調中爲我提供'數據',但是它不會返回/渲染另一個地圖本身的組件,或者將回調中的'數據'傳遞給另一個組件。 –