[英]react function is not defined no-undef
嘗試編譯我的應用程序時出現以下錯誤 - 'getRestaurants'未定義no-undef
我無法追蹤為什么沒有為zipCodeToCoords定義getRestaurants
我有一個輸入組件,提交郵政編碼並調用zipCodeToCoords,然后我想調用getRestaurants
這是主要的反應成分
class App extends Component {
constructor(props){
super(props);
this.state = {
restraunts:[],
selectedRestraunt:null
}
}
getRestaurants(lat,lon){
var url = "https://developers.zomato.com/api/v2.1/geocode?lat="+lat+"&lon="+lon;
$.ajax({
url:url,
headers:{
'Accept': 'application/json',
'user_key': 'MY KEY'
}
}).done(function(data){
console.log(data);
});
}
zipCodeToCoords(zip){
var url = "https://www.zipcodeapi.com/rest/MYKEY/info.json/"+ zip +"/degrees";
$.ajax({
url:url,
}).done(function(data){
console.log(data.lat);
getRestaurants(data.lat,data.lng);
});
}
render() {
return (
<div className="App">
<div className="row">
<div className="columns large-9">
<Input onSearchTermSubmit={this.zipCodeToCoords} />
</div>
</div>
<div className="row">
<div className="columns large-9">
<RestrauntInfo />
</div>
<div className="columns large-3">
<RestrauntList />
</div>
</div>
</div>
);
}
}
這是輸入組件
class Input extends Component{
constructor(props){
super(props);
this.state = {zip:''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
event.preventDefault();
this.props.onSearchTermSubmit(this.state.zip);
}
handleChange(event){
this.setState({zip:event.target.value});
}
render(){
return(<div>
<form onSubmit={this.handleSubmit}>
<div className="input-group">
<span className="input-group-label">Enter Zip Code</span>
<input className="input-group-field" type="number" value={this.state.zip} onChange={this.handleChange} />
<div className="input-group-button">
<input type="submit" className="button" value="Submit" />
</div>
</div>
</form>
</div>);
}
}
獲取餐館不是一些全局功能,它是您的App類的一種方法,因此您需要這樣調用它。 解決這個問題的最簡單方法可能是:
this.getRestaurants
在zipCodeToCoords
this
綁定到你的構造函數中的getRestaurants
和zipCodeToCoords
,即zipCodeToCoords
this.getRestaurants = this.getRestaurants.bind(this);
zipCodeToCoords
this.getRestaurants = this.getRestaurants.bind(this);
回調將變為:
done((data) => {
console.log(data.lat);
this.getRestaurants(data.lat,data.lng);
});
這看起來是一個范圍問題,因為您傳遞的是zipCodeToCoords
它的范圍來自調用它的位置,而不是您想要的位置。 要解決此問題,您可以使用.bind,或者如果您正在轉換應用程序,則可以將其更改為箭頭功能。
zipCodeToCoords = (zip) => {
...
}
您還需要更改getRestaurants(data.lat,data.lng);
從范圍調用它this.getRestaurants(data.lat,data.lng);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.