繁体   English   中英

如何获取 ReactJS 中的 api 数据?

[英]how to fetch api data in ReactJS?

我试图在 reactjs 中获取 api 数据,但数据没有按预期完美加载,而不是我得到一个空页面。 下面是我的源代码;
我可能是 reactjs 的新手,如果有人能在我做错的地方帮助我,那就太好了。 非常感谢你。

端点网址: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>

检查此代码。

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;
var page = (
  <div>
    <h1>loading...</h1>
  </div>
);
if (bloglist.length > 0)
  page = bloglist.map((bloglistEntry) => {
    return (
      <React.Fragment key={bloglistEntry.id}>
        <h3 className='mb-2'>
          <a href='single.html'>{bloglistEntry.title}</a>
        </h3>
        <p className='mb-4'>{bloglistEntry.description}</p>
      </React.Fragment>
    );
  });
return page;
  }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM