Javascript 如何显示从API请求的对象
我试图用API中的每个类别显示不同的卡片(名称、子类别…)。但我看不出API中的值是什么。例如,我不知道ID是什么,或者类别名称是.title还是.name,所以我无法显示它 在API上,我可以看到类别的名称,但没有“ID”、“名称”、“键”。。。因此,当我试图显示它时,我不知道如何访问该名称Javascript 如何显示从API请求的对象,javascript,reactjs,api,axios,Javascript,Reactjs,Api,Axios,我试图用API中的每个类别显示不同的卡片(名称、子类别…)。但我看不出API中的值是什么。例如,我不知道ID是什么,或者类别名称是.title还是.name,所以我无法显示它 在API上,我可以看到类别的名称,但没有“ID”、“名称”、“键”。。。因此,当我试图显示它时,我不知道如何访问该名称 componentDidMount() { axios.get('/categories') .then(res => { const categories = res.dat
componentDidMount() {
axios.get('/categories')
.then(res => {
const categories = res.data; //How do I get the "ID" from here?
this.setState({categories: categories});
})
}
把它扔进你的控制台,看看它可能是什么
componentDidMount(){
axios.get(“/categories”)
。然后(res=>{
const categories=res.data;//如何从这里获取“ID”?
log({res,categories})//试试这个!
this.setState({categories:categories});
})
}
您的CDM将存在于您的类中,因此您还有一个render()方法:
render(){
返回(
{Object.keys(this.state.categories).map((key)=>{
{key}{this.state.categories[key]}
}
);
}
这将显示一个键列表,其中包含数据中的值。将res.data分配给状态后
axios.get('/categories')
.then(res => { this.setState({ categories: res.data }) })
.catch(err => { console.log(err) })
您可以在console.log“this.state.categories”中查看是否有任何id/名称详细信息
这取决于你的数据库
编辑:
因为我检查了你的API,没有id字段。所以你不能访问id。
但是
将为您提供服装对象。
您可以在对象中使用唯一的项作为键。如果您尝试一个示例代码,例如:
componentDidMount() {
const endpoint = 'https://www.ifixit.com/api/2.0/categories';
fetch(endpoint).then(res => console.log(res.json()));
}
单击(F12)打开控制台,您将看到返回一个Promise
,但ID
对象不存在
您是否尝试制作一个
控制台.log(res);
来查看响应中出现了什么?或者使用chrome开发工具停止在“const categories=res.data”上。这样您就可以看看您得到了什么
this.state.categories.Apparel
componentDidMount() {
const endpoint = 'https://www.ifixit.com/api/2.0/categories';
fetch(endpoint).then(res => console.log(res.json()));
}