【问题标题】:Best way to handle component loading in react在反应中处理组件加载的最佳方法
【发布时间】:2020-06-13 06:53:56
【问题描述】:

我有一个从 JSONPlaceholder 获取帖子的应用。它具有帖子的初始状态:[]。然后它调用:

this.setState({posts})

如果我想在组件接收帖子之前渲染加载...是不是更好说:

if (!this.state.posts.length) // Do something

或者最好将 loading: true 添加到初始状态,然后如果组件接收到数据没有错误,则这样说:

if(!this.state.loading) // Do something

【问题讨论】:

  • 在我看来,在 state.loading 上显示加载器是一个好方法,因为当 state.posts.length 不为零时,如果您将更多记录加载到 state.posts 中,它将允许您显示加载器.

标签: reactjs axios loading jsonplaceholder


【解决方案1】:

首先,正如评论所说,使用单个 boolean type state 比在任何地方使用 changeable condition 更好。

如果您想添加一些loading animation,我有时尝试过Material-UI processing,这很方便。

并且在这种情况下使用非常简单。添加conditional rendering 就完成了。

import { CircularProgress } from '@material-ui/core';
...
render() {
  const { loading } = this.state;
  return (
    ...
    {loading ? <CircularProgress /> : <YourComponent /> ... 
    ...
  )
}

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 2019-05-03
    相关资源
    最近更新 更多