如何在响应本机的fetch API中等待服务器响应时执行操作?

时间:2017-10-22 13:27:20

标签: react-native fetch-api

The React Native docs显示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;
    })
    .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);
    });
 }

1 个答案:

答案 0 :(得分:2)

通常通过更新状态来解决这个问题。像这样:

取:

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将足够智能以重新呈现您的视图。