2016-07-08 24 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。地理编码器函数可以工作,并在回调中为我提供'数据',但是它不会返回/渲染另一个地图本身的组件,或者将回调中的'数据'传递给另一个组件。 –