【问题标题】:Changing what component returns after it completes a long operation更改完成长时间操作后返回的组件
【发布时间】:2021-04-08 21:11:58
【问题描述】:

我的组件如下所示:

export default function MyComponent(){        
    //long async operation
    //return something that is set inside the async operation
}

由于异步操作需要一些时间,return 语句在异步任务结束之前运行,因此它返回不完整的内容。

如何更改组件在随机长异步操作(或承诺)结束后返回的内容?

【问题讨论】:

  • 有一个更大、更惯用(也更用户友好)的解决方案。当您必须获取数据时,您必须保持某种状态——即数据是正在加载还是已完成获取。根据该状态,您会显示一个正在加载的 UI,然后在准备好显示内容 UI 时更新状态/重新渲染

标签: reactjs async-await promise


【解决方案1】:

使用状态来确定数据何时加载/完成/失败

export default function MyComponent(){
   const [loading, setLoading] = React.useState(false);
   const [data, setData] = React.useState(null);
   const [error, setError] = React.useState(null);
   React.useEffect(() => {
      setLoading(true);
      longAsyncOperation()
        .then((data) => {
            setData(data);
        })
        .catch((error) => {
            setError(error);
        })
        .finally(() => {
            setLoading(false);
        });
   }, []);        
 
   return isLoading 
      ? (<div>Loading</div>) 
      : error || !data ? (<div>{error.message}</div>)
      : (<div>Complete!</div>)

}

【讨论】:

    【解决方案2】:

    您必须使用状态并在异步操作结束后对其进行更新:

    export default function MyComponent(){
      const [loading, setLoading] = useState();        
      setLoading(true);
        //long async operation
      setLoading(false);//this should run once the async operation has finished
        //return something that is set inside the async operation
      return loading ? <LoadingComponent /> : <MyView />;
    }

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2016-04-22
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多