简体   繁体   English

在我们等待响应时如何显示加载器,如果没有数据来显示消息“没有可用数据”?

[英]How to display loader while we wait for the response and if no data comes display a message “No data available”?

I am trying to fetch data from a url.我正在尝试从 url 获取数据。 I need to display a loader while we wait for the response and I need to display a message "No data available" when an empty array comes as response.当我们等待响应时,我需要显示一个加载器,并且当一个空数组作为响应时,我需要显示一条消息“没有可用的数据”。

fetch(url).then(res => res.json())
          .then(result => {
                     if(!result.error){this.state.dataStore.resultArr = result}
           })

In the above code, I am assigning the result to a variable resultArr in the MobX Store with name dataStore.在上面的代码中,我将结果分配给 MobX Store 中名为 dataStore 的变量 resultArr。

<>
  {
  resultArr && resultArr.length>0 ? 
  ( resultArr.map(ele => ( <div>{ele.Username}<div>))) : (<Loader />)
  }
</>

Here till the response comes, I displayed a loader, but this is not covering the case when the data is an empty array.在响应到来之前,我显示了一个加载器,但这不包括数据为空数组的情况。 I tried various possibilities by taking an extra variable to check if the data is an empty array, but they are failing in some case.我通过使用一个额外的变量来检查数据是否为空数组来尝试各种可能性,但在某些情况下它们会失败。 What should I do to display a loader till the response comes and if it is empty a message should be displayed and loader should be turned Off.在响应到来之前我应该怎么做才能显示加载器,如果它是空的,应该显示一条消息并且应该关闭加载器。

You need a new variable to record the loading status.您需要一个新变量来记录加载状态。

this.setState({ fetching: true });
fetch(url).then(res => res.json())
          .then(result => {
                     if(!result.error){this.state.dataStore.resultArr = result}
           })
           .finally(() => {
              this.setState({ fetching: false });
           })
render() {
  if (fetching) return <Loader />;
  return (
    <>
      {
      resultArr && resultArr.length>0 ? 
      ( resultArr.map(ele => ( <div>{ele.Username}<div>))) : (<Empty />)
      }
    </>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM