如何在ReactJS中获取api数据?

我试图在reactjs中获取api数据,但是数据没有按预期加载,而不是结果是空页面。下面是我的源代码; 我可能对Reactjs还是陌生的,如果有人在我做错事情的地方帮我,那将是很棒的。提前非常感谢您。

endpoint_url : http://localhost:8000/api/blog_list

api数据:

[
    {
        "id": 1,
        "url": "http://localhost:8000/api/blog_detail/brown",
        "title": "brown",
        "slug": "brown",
        "image": "http://localhost:8000/media/blog/image_2.jpg",
        "description": "",
        "created_on": "2020-05-08T15:20:53Z",
        "status": true,
        "category": [
            1
        ]
    },
    {
        "id": 2,
        "url": "http://localhost:8000/api/blog_detail/black",
        "title": "black",
        "slug": "black",
        "image": "http://localhost:8000/media/blog/loc.png",
        "description": "",
        "created_on": "2020-05-08T17:14:31Z",
        "status": true,
        "category": [
            2
        ]
    }
]

./src/Base.js

export default class App extends Component{

  state = {
    bloglist:[]
  };

  componentDidMount(){
    this.fetchData()
  }

  fetchData = async () => {
    try{
      const response = await fetch("http://localhost:8000/api/blog_list");
      const jsonResponse = await response.json()
      this.setState({bloglist:jsonResponse})
    }
    catch(error){
      console.log(error)
    }
  }

  render(){
    const {bloglist} = this.state
    if(!bloglist){
      return (
        <div>
          <h1>loading...</h1>
        </div>
      )
    }

    return (
      {
        bloglist.map(bloglist => (
          <h3 class="mb-2">
            <a href="single.html">{bloglist.title}</a>
          </h3>
          <p class="mb-4">{bloglist.description}</p>
          ))
      }
    )
  }
}



评论
爱到何时
爱到何时

将其包装在div或。 React需要一个元素。

<h3 class="mb-2">
   <a href="single.html">{bloglist.title}</a>
   </h3>
<p class="mb-4">{bloglist.description}</p>
点赞
评论