【问题标题】:If statement with db response带有 db 响应的 if 语句
【发布时间】:2016-10-11 18:40:09
【问题描述】:

打开了一个新问题:Meteor / ReactJS - UI blinking issue: rendering twice before and after checking a database

NEW ISSUE 有更详细的例子


Meteor + ReactJS App:我需要检查一个数据库(集合)是否已经有一个值,并根据它决定显示什么。

这是我所拥有的:

render() {

    if (this.props.companies.length) {
        return (
          <div className="container">

            {this.renderCompanies()}

          </div>
        );
    } else {
        return (
          <div className="container">

            <header id="addCompanyForm">
              <h1>Add Company</h1>

              <form onSubmit={this.handleSubmit.bind(this)} >
                <input
                  type="text"
                  ref="companyName"
                  className="form-control"
                  placeholder="Type a new company name"
                />
              </form>
            </header>

          </div>
        );
    }
  }

我的问题:this.props.companies.length 是 0、0,如果我的收藏中已经有一家公司,它只有第三次变成 1。因此,它会在第一秒显示表单,然后在最终接收到集合值并更改公司详细信息时将其隐藏。我怎样才能在第一秒消除闪烁并立即显示正确的语句。我也尝试了 React 生命周期 + 会话,但没有任何帮助。

【问题讨论】:

  • 您是否使用createContainer 从数据库中获取数据?
  • 是的 - createContainer(() => { ... }
  • Meteor 和 ReactJS 已在标签中注明 - 无需将它们添加到标题中。

标签: reactjs meteor react-jsx


【解决方案1】:

听起来,您有一个 ajax 调用正在获取所有公司,而这正在发生时,company.length 为 0,它会呈现表单。一旦 api 响应返回,公司就会被填充信息,表单就会消失。

如果是我,我会在 api 调用发生时处于加载状态,并显示某种占位符,表明正在加载,然后在加载完成时渲染实际组件,检查是否有公司,如果有,请以其他方式显示表格。

您不必制作第三个组件,您可以执行以下操作:

render() {
 // depending where the ajax call is happening would depict if this is a state or a prop for loading...
  if (this.props.loading) {
    return <div> Loading companies...</div>
  }

  // rest of your logic goes here for if companies.length
}

【讨论】:

  • 它没有帮助,没有区别。它实际上甚至没有尝试为加载语句显示加载 div
  • 嗨,我在此基础上创建了另一个问题,其中包含更多详细信息:stackoverflow.com/questions/40194938/…
猜你喜欢
  • 2012-01-27
  • 2016-08-15
  • 2014-10-26
  • 2018-02-20
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多