在 React Native 的 fetch API 中等待服务器响应时如何执行操作?
How do I perform actions while waiting for server response in react native's fetch API?
The React Native docs 显示以下用于 React-Native 获取的代码 API:
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 将足够聪明地重新呈现您的视图。
The React Native docs 显示以下用于 React-Native 获取的代码 API:
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 将足够聪明地重新呈现您的视图。