【问题标题】:Fetching before render with multiple fetch request使用多个获取请求在渲染之前获取
【发布时间】:2020-08-06 22:13:38
【问题描述】:
import React from "react";

class Admin extends React.Component {
  state = {
    isFetching: true


  }

  componentDidMount = () => {

    this.getProfile()
    this.getPost()
    this.setState({isFetching: false})




  }

 getProfile = () => {
     fetch(url)
     .then (fetch stuff)

 }


 getPost = () => {
     fetch(url)
     .then (fetch stuff)

 }


  render() {

    if (this.state.isFetching) {
      return <div>Loading...</div>
    } else {
      return (

        <div>



        </div>

      );
    }
  }
}

export default Admin;

目标基本上是我想获取我的所有数据然后渲染。我将 isFetching 状态设置为 true,因此它只返回加载时间,因为如果它呈现未获取,它会出错。

此当前代码不起作用。它仍然呈现未完全获取的未完全数据。如何确保 isFetching 仅在获取每个数据后才变为 false。 (我有 2 个获取函数)

【问题讨论】:

    标签: reactjs fetch


    【解决方案1】:

    使用异步/等待获取

     getProfile = async () => {
         const profile = await fetch(url)
         return profile //or whatever you need to do with it
    
     }
    
     getPost = async () => {
         const post = await fetch(url)
         return profile //or whatever you need to do with it
    
     }
    

    【讨论】:

    • 那也没用。我认为这是因为在 .then (fetchStuff) 中我在此块内设置状态,即 this.setState({users: response.json})。
    猜你喜欢
    • 2021-01-31
    • 2021-06-26
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2020-02-12
    • 1970-01-01
    相关资源
    最近更新 更多