[英]How can I pass variable in my fetch request
我正在使用本機反應並嘗試理解一些示例。
我有問題
我試圖在我的抓取中傳遞緯度,但我遇到了一個問題,他說我的“緯度”不存在
class App extends React.Component {
constructor() {
super();
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
markers: [],
loaded: false
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
);
this.getLocations()
}
getLocations(){
return fetch('https://***&geofilter.distance='+latitude+'%2C2.3883402698750875%2C2000') //here
.then(response => response.json())
.then(responseData =>{
var markers = [];
你能幫幫我嗎,謝謝:)
在getLocations
中,您嘗試使用latitude
變量,但那里沒有范圍。 您可能想要this.state.region.latitude
。
但是,如果您嘗試使用this.state.region.latitude
,則需要將調用移至componentDidMount
中的getLocations
,以便它位於狀態更改完成處理程序中:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}
},
() => { // ***
this.getLocations(); // ***
}); // ***
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
);
// *** Not here
}
您正在將緯度存儲在狀態中,因此您需要將其稱為this.state.region.latitude
return fetch('https://***&geofilter.distance='+this.state.region.latitude+'%2C2.3883402698750875%2C2000')
嘗試像這樣使用您的提取:
return fetch('https://***&geofilter.distance='+this.state.region.latitude+'%2C2.3883402698750875%2C2000')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.