首页 > 解决方案 > 使用 React 获取 API 数据

问题描述

我有一个反应,它使用 django rest 框架 API。我要获取 JSON 数据,但似乎我没有正确获取信息,或者我没有以正确的方式呈现:

import React, { Component } from 'react' ;
class App extends Component {
  state = {
    todos: []
  };
async componentDidMount() {

fetch('http://127.0.0.1:8000/api/todos/')
.then(results =>{
  console.log(results)
  const get_todos = results.map( c=>{
    return {
      id: c.id,
      title: c.title,
      descripttion: c.title
    };
  });

  const newstate = Object.assign({},this.state,{
      todos: get_todos
    });
    this.setState(newstate);
  }).catch(error=> console.log(error));
}
render(){
  return (
    <div className="App">
       {this.state.todos} 
    </div>
  )
 }
}
export default App;

标签: reactjsdjango-rest-framework

解决方案


它应该是

state = { loading : true }
componentDidMount() {
 fetch('http://127.0.0.1:8000/api/todos/')
  .then(blob => blob.json())
  .then(response => {
    ...
  })
}

推荐阅读