我是JS和ReactJS的新手,我尝试获取一个给我这样的JSON对象的终结点:
{"IDPRODUCT":4317892,"DESCRIPTION":"Some product of the store"}
我通过此端点获取此JSON对象:
http://localhost:3000/product/4317892
但是我没有如何在我的React应用程序中使用它,我想使用这些数据在页面上显示它们
我当前的代码看起来像这样,但是它不起作用,而且我肯定也不行:
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,这将获取数据并显示它们
谢谢大家
您的州没有postItems
考虑undefined
到的属性,因此不会做出反应。在您的情况下,无需定义新const
状态并直接使用状态。
同样,当您使用时setState()
,您需要告诉它应将值设置为哪个状态属性。
componentWillMount() {
fetch('http://localhost:3000/product/4317892')
.then(res => res.json())
.then(res => {
this.setState({
...this.state, // Not required but just a heads up on using mutation
posts: res
})
})
.catch((error => {
console.error(error);
}));
}
render() {
console.log(this.state)
return (
<div>
<p><strong>Id: {this.state.posts.IDPRODUCT}</strong></p>
<p>Description: {this.state.posts.DESCRIPTION}</p>
</div>
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句