【问题标题】:handle loading and no content separately分别处理加载和无内容
【发布时间】:2017-06-30 01:28:51
【问题描述】:

在我的应用程序中,我从 API 获取内容。我可以显示内容并显示加载器图标,直到内容未加载。但是如果没有任何内容,页面会显示加载器图标,这是意外的。如果根本没有内容,则预期的功能是不显示可用的内容。

render() {
    const { logs } = this.state;
    if (logs.size === undefined) {
      return <div>No Logs</div>;
    } else if (isEmpty(logs)) {
      return (
        <div className="earth-spinning">
          <img src={EarthSpinning} alt="spinner" style={{ margin: "0 auto" }} />
        </div>
      );
    } else {
      return (
        <div>
          <h2>Logs</h2>
          <button onClick={() => this.props.deleteLogs()}>
            Delete All Logs
          </button>
          <ul className="list-group">
            {this.renderLogs()}
            {this.state.show ? this.props.dialog : null}
          </ul>
        </div>
      );
    }
  }

这是我得到的数据

【问题讨论】:

  • 什么是isEmpty,您能否给我们一份来自 API 的内容示例?
  • 更新了我的问题。 isEmpty 正在检查对象是否为空。
  • @AndrewLi 了解更多详情,可以到以下链接gist.github.com/anonymous/e1dd5e91297108dadcc6e61d3c08a394
  • 请注意,将道具存储在您的状态中被认为是一种反模式。最好在将日志作为 props 传递给组件之前将其转换为纯 JS,或者在需要时将其作为纯 JS 执行
  • 你能把我提供给你的要点注释掉吗?

标签: javascript reactjs redux immutable.js


【解决方案1】:

让 API 返回 Promise 非常好,这样您就可以在它们完成时做出响应

这个例子假设你会做你的 API 调用,数据会去一个商店,然后进入道具

...

getInitialState() {
    return {
        loading: true
    };
}

componentWillMount() {
   this.props.requestLogs()
       .then(() => this.setState({ loading: false });
}

render() {
    if (this.state.loading) {
        return this.renderLoading();
    }

    if (this.props.logs.length === 0) {
        return this.renderEmptyView();
    }

    return this.renderStuff();
}

【讨论】:

  • 我收到TypeError: this.props.requestLogs(...).then is not a function 错误
  • 在 componendDidMount 和 WillMount 中都尝试过,但在任何地方都没有工作
  • this.props.requestLogs 需要是一个返回承诺的函数。
  • 我不确定你的 api 在logRequest 中调用了什么,但也许可以看看fetch apipromises
猜你喜欢
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多