【发布时间】:2025-12-21 22:30:11
【问题描述】:
我对 JS 和 ReactJS 很陌生,我尝试获取一个端点,它给了我一个这样的 JSON 对象:
{"IDPRODUCT":4317892,"DESCRIPTION":"Some product of the store"}
我通过这个端点得到这个 JSON 对象:
http://localhost:3000/product/4317892
但我不知道如何在我的反应应用程序中使用它,我想使用这些数据在页面上显示它们
我当前的代码看起来像这样,但它不工作,我肯定也不好:
import React, {Component} from 'react';
class Products extends Component {
constructor(props){
super(props);
this.state = {
posts: {}
};
};
componentWillMount() {
fetch('http://localhost:3000/product/4317892')
.then(res => res.json())
.then(res => {
this.setState({
res
})
})
.catch((error => {
console.error(error);
}));
}
render() {
console.log(this.state)
const { postItems } = this.state;
return (
<div>
{postItems}
</div>
);
}
}
export default Products;
console.log(this.state)里面有数据,但是我现在很迷茫,不知道怎么办
既然我在这里,我还有一个问题,我想在我的 App.js 中输入一个输入,用户将能够输入产品的 id 并获得一个,我该如何做到这一点?将数据从 App.js 传递给 Products.js,后者将获取数据并显示它们
提前谢谢大家
【问题讨论】:
-
您使用
posts作为属性初始化state。然后你setState一个名为res的属性。最后在render中解构state并尝试提取名为postItems的属性。那么哪个是正确的名字呢?请准确发布从console.log(this.state)记录的内容 -
感谢@Gilsdav 的回答,我确实纠正了它
标签: javascript json reactjs fetch