[英]How to setStates before api Call in React
我的應用程序(用react-native制作)有一個小問題,當用戶打開應用程序時,我有方法componentDidMount,該方法通過使用this.setState重新加載緯度和經度狀態。
在那之后,我有一個函數將緯度和經度發送給我。 但是,當用戶進行連接時,在setState和函數調用之間的時間非常短,因此我的第一個API調用未定義,因為該狀態在API調用之前不是最新的。 我不知道狀態更新后在哪里放置我的函數。
componentWillMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
lat: position.coords.latitude,
long: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
setTimeout(() => {
const {lat, long} = this.state
console.log(lat)
this.props.getConditions(lat, long)
}, 1000)
}
即使使用setTimeout,console.log也將返回null(對應於我的初始狀態)
謝謝你的幫助
componentWillMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
lat: position.coords.latitude,
long: position.coords.longitude,
error: null,
}, () => {
this.props.getConditions(lat, long)
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
這應該可以解決您的問題,將回調傳遞給setstate在狀態更新完成后運行該回調。 setState是異步的。
通常, setState
以異步方式工作。 這意味着在調用setState之后,不會立即更改this.state變量。 因此,如果要在狀態變量上設置狀態后立即執行操作,然后返回結果,則回調將很有用。
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
lat: position.coords.latitude,
long: position.coords.longitude,
error: null,
}, () => {
this.props.getConditions(lat, long)
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
閱讀更多有關何時使用setState回調的信息 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.