【问题标题】:React await async or rerender?反应等待异步还是重新渲染?
【发布时间】:2020-06-14 08:30:09
【问题描述】:

我有一个组件可以渲染从服务器接收到的数据。

我可以想到在这种情况下使用 2 个选项。

  1. componentDidMount() 中触发 fetch 函数并使用初始(空)数据进行渲染,并在设置状态时让 redux 重新渲染
  2. await in componentDidMount() 并等待服务器响应,然后使用接收到的数据进行渲染

Option1 在没有数据的情况下加载会稍微快一些,然后用数据重新渲染(总共 2 个),Option2 只会渲染一次,但组件会显示得更慢。

哪种方法更好?

【问题讨论】:

    标签: reactjs asynchronous redux async-await render


    【解决方案1】:

    这取决于您的设计/需求。

    一种正常的方法是为请求添加loading 动画(如material-ui loading)。并且仅在达到响应时呈现。

    async componentDidMount() {
      await this.request();
    }
    async request() {
      const req: ReqParamsType = {
        ...
      }
      this.setState({loading: true});
      await this.props.getReports(req);
      this.setState({loading: false});
    }
    
    render() {
      const { loading } = this.state;
      return (
        {loading ? <LoadingAnimation /> : <MainContent />}
        ... 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多