[英]in react native app get location and call a state updating function
我想按順序調用一個函數。 所以第一次嘗試setTimeout
它有效但似乎很慢。
那我提醒無極。 我認為這是一個很好的解決方案,但事實並非如此。
這是我寫的代碼和我注釋掉的承諾部分。
我想要做的是調用_getLongLat()
然后調用_getData()
函數。 因為得到位置
需要時間,結果我沒有更新組件。
_onPress = () => {
this._getLongLat();
setTimeout(this._getData,500);
//let promise = new Promise(()=>{this._getLongLat()})
//promise.then(()=>{this._getData()});
}
這是 _ getLongLat()
和_getData()
_getLongLat = () => {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({...this.state, location:{ longitude: position.coords.longitude, latitude: position.coords.latitude }});
}, (error) => {
this.setState({message: error.message})
}, { enableHighAccuracy: true, timeout: 10000, maximumAge: 60*60})
};
_getData = () => {
GetWeather.getWeather(this.state.location.latitude, this.state.location.longitude).then( json => {
this.setState({...this.state, data: json });
console.log(this.state);
});
};
#
這是_onPress()
工作代碼
_onPress = () => { this._getLongLat() .then( position => { this.setState({ location: {longitude: position.coords.longitude, latitude: position.coords.latitude} }) return this._getData( position.coords ); }).then(json => { console.log(json); this.setState({ ...this.state, data: json }); }) .catch(error => this.setState({ message: error.message})); }
您可以嘗試使用以下代碼。 我正在使用最新版本的 react native 所以這就是為什么我需要安裝npm i @react-native-community/geolocation
。 如果您使用舊版本的 react native,則無需安裝 npm。 請在 promise 中添加您的代碼,並在resolve
返回響應並在reject
返回錯誤。 自 RN 0.60 起,Geolocation 模塊已從 RN Core 遷移。有關信息,請查看以下鏈接:-
https://www.npmjs.com/package/@react-native-community/geolocation
用新版本的 react native>0.60.0 試試這個代碼
_getLongLat = () => {
return new Promise((resolve, reject) => {
Geolocation.getCurrentPosition(info => info?resolve(info) :reject('Error'));
});
};
componentDidMount() {
this._getLongLat().then(value => {
alert(JSON.stringify(value));
});
}
用舊版本的 react native<0.59.0 試試這個代碼
像這樣改變_onPress
_onPress = () => {
this._getLongLat().then(value => {
this._getData(value);
});
};
像這樣改變_getLongLat()
和_getData()
_getLongLat = () => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
position => {
resolve(position);
},
error => {
reject(error.message);
},
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 60 * 60 }
);
});
};
_getData = value => {
GetWeather.getWeather(value.coords.latitude, value.coords.longitude).then(
json => {
this.setState({ ...this.state, data: json });
console.log(this.state);
}
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.