reactjs - 使用 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;
解决方案
它应该是
state = { loading : true }
componentDidMount() {
fetch('http://127.0.0.1:8000/api/todos/')
.then(blob => blob.json())
.then(response => {
...
})
}
推荐阅读
- c - 使用长变量存储字符并打印
- linux - bash while 循环中的“完成”功能/含义是什么?
- azure - Microsoft Azure 基础 Pdf 版
- apache-spark - 将 Dataset 中的嵌套 json 字符串转换为 Spark Scala 中的 Dataset/Dataframe
- ios - 将 IAP 存储在 UserDefaults 中,这样用户就不需要在每次按下“可购买”按钮时恢复购买
- c++ - 析构函数中的 delete[]:指定给 RtlValidateHeap 的地址无效
- react-native - 如何压缩刚用 React Native Expo 拍摄的图片
- flutter - HTTP 请求结果不可见
- javascript - React Native useEffect 在异步函数中的使用
- java - 获取java对象变量名的值