React native 在react native';中等待服务器响应时如何执行操作;什么是获取API?
显示React Native的fetch API的以下代码:React native 在react native';中等待服务器响应时如何执行操作;什么是获取API?,react-native,fetch-api,React Native,Fetch Api,显示React Native的fetch API的以下代码: function getMoviesFromApiAsync() { return fetch('https://facebook.github.io/react-native/movies.json') .then((response) => response.json()) .then((responseJson) => { return responseJson.movies;
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
我要找的是在fetch
调用服务器时放置加载脚本之类的东西的地方,类似于以下非工作代码:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.whileWating(() => {
// This is the type of thing I want to put into the fetch
console.log('Waiting for the server response.')
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
通常解决这个问题的方法是更新状态。像这样: 获取:
this.setState({isLoading: true});
fetch(url)
.then((response.json()))
.then((responseJson) => this.setState({isLoading: false}));
然后在渲染方法中,执行如下操作:
if (this.state.isLoading){
return this.myLoadingView();
} else {
return this.myViewWithCompletedData()
}
抓取完成后,状态将更新,RN将足够智能,可以重新渲染视图