获取 API 回调以在 ReactJS 中的函数外部传递
Getting API callback to pass outside of function in ReactJS
>我无法让数据通过第 72 行(我用断线标记)。到目前为止,一切都很好(来自数据库的数据正在传递到"google-geocoder",而"geoPlace"对象正在通过"data"参数中的回调,但是当我尝试访问"geocoder"函数"数据"之外的"数据"时,"数据"变得未定义。我已经尝试过.bind,setState,window等。一切都没有运气。我觉得这是一个范围问题,但不确定。任何帮助将不胜感激。谢谢。
// 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;
这是因为您尝试在接收这些属性之前访问组件的属性。
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>
)
}
});
我希望这有所帮助。
相关文章:
- 访问函数外部的变量
- appendChild在函数外部工作,但在函数内部不工作
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- JavaScript未定义的函数外部JavaScript文件
- 没有在函数外部分配全局变量
- 在挖空中引用对象构造函数外部视图模型的属性
- 访问函数外部的变量
- JS:从函数外部调用变量
- 在函数外部的 Angularjs 中访问 $http.get 的结果
- JQuery 更改函数外部的变量值
- 函数外部的 clearTimeout() 无法正常工作
- Javascript - 无法获取函数来设置要在函数外部使用的全局变量
- 如何设置 var self = this;从函数外部
- 在 JavaScript 中维护函数外部变量的值
- 为什么匿名函数中的私有变量可以从 javascript 中的函数外部访问
- 如何在函数外部获取变量的值
- 如何在函数外部访问 Javascript 变量值
- 节点.js在函数外部获取 MySQL 的结果
- 如何使用 $http.get 每 3 秒发出一个新请求并在函数外部获取数据
- 在 Phonegap DB 函数中返回函数外部的变量