如何从json获取对象数组
这是api,, 我正试图使用fetch方法从中获取数组结果,但得到一个错误,即无法获取未定义的值如何从json获取对象数组,json,reactjs,Json,Reactjs,这是api,, 我正试图使用fetch方法从中获取数组结果,但得到一个错误,即无法获取未定义的值 import React, { Component } from 'react'; class App extends Component { constructor() { super() this.state = { books: [] } } componentDidMount() { fetch('http://skunkworks
import React, { Component } from 'react';
class App extends Component {
constructor() {
super()
this.state = {
books: []
}
}
componentDidMount() {
fetch('http://skunkworks.ignitesol.com:8000/books/')
.then(res => res.json())
.then(data => this.setState({ books: data }))
.catch(e => {
console.log(e);
return e;
});
}
render() {
let book = []
book = this.state.books.results;
console.log(book[0])
return (
<div>
<h1>Books</h1>
</div>
)
}
}
export default App;
import React,{Component}来自'React';
类应用程序扩展组件{
构造函数(){
超级()
此.state={
书籍:[]
}
}
componentDidMount(){
取('http://skunkworks.ignitesol.com:8000/books/')
.then(res=>res.json())
.then(data=>this.setState({books:data}))
.catch(e=>{
控制台日志(e);
返回e;
});
}
render(){
let book=[]
book=this.state.books.results;
console.log(书籍[0])
返回(
书
)
}
}
导出默认应用程序;
这是我的密码
我还注意到json数据通常类似于[{}],但这里是{}格式。
请向我推荐一些解决方案……正如我从您的url链接中看到的,您的json数据数组存在于API返回对象的结果键中 因此,如果你只对结果感兴趣,你应该这样做:
从“React”导入React,{Component};
类应用程序扩展组件{
状态={
书籍:[]
}
异步组件didmount(){
const objectFromUrl=wait fetch('http://skunkworks.ignitesol.com:8000/books/')
const data=await objectFromUrl.json()//第一种方式
//或者可以使用解构方式
const{results}=wait objectFromUrl.json()//第二种方法
这是我的国家({
books:data.results//results键包含对象数组中的“[{}]”数据
})
}
render(){
const{books}=this.state
返回(
书
{books.map(book=>(
{book.id}
)}
);
}
//您可以再次使用解构来获取您感兴趣的唯一密钥
render(){
const{books}=this.state
返回(
书
{books.map({id,formats})=>(
{id}
{格式[ˋapplication/pdf']}
)}
);
}
}
看起来您需要在结果数据上运行一个循环。我在结果部分看到的数据实际上是json数据。url调用提取的不仅仅是这些数据。我对reactjs不太熟悉,但看起来您可能需要执行类似于循环的操作,以将数据输出到各个json对象中。下面是一个基本示例c示例获取数据并对其进行操作,我建议您阅读本快速教程,是的,现在我可以获取结果数组,但如何从结果中获取对象格式。您必须像在render方法中一样迭代books数组并提取每本书的格式。我编辑了答案,但它只显示idIt,因为您创建html标记以显示它。在我的答案中,我显示«application/pdf»,但您可以用任何格式的键替换对象告诉我您想要的显示结果,我将编辑我的答案