【问题标题】:React doesn't display without conditional rendering from api没有来自 api 的条件渲染,React 不会显示
【发布时间】:2021-12-14 21:09:58
【问题描述】:

当我从 api 获取数据时,为什么组件不呈现/显示任何内容? 下面的代码只是给了我一个空白页

 render(){
    return (
      <div>
        <p>{this.state.character[0]}</p>
      </div>
    )
  }

但是当我进行一些条件渲染时,它会显示数据。

 render(){
    return (
      <div>
        {<p>{this.state.character? this.state.character[0] : null}</p>}
      </div>
    )
  }

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您如何获取数据?在componentDidMount() 希望。 componentDidMount() 在render() 之后运行,意思是,当组件第一次加载/挂载时,没有数据。数据被接收,然后在组件安装后添加到状态

    【讨论】:

      【解决方案2】:

      来自 API 的数据需要时间来加载,因此第一个代码没有任何数据,因为来自 API 的请求未完成。您无法访问其中没有任何内容的索引。所以条件基本上是可以安全展示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        • 2019-11-30
        • 1970-01-01
        • 2019-05-03
        • 1970-01-01
        • 2019-10-06
        相关资源
        最近更新 更多