javascript - 显示来自 Get 请求的元素
问题描述
我目前正在尝试学习 React,并正在尝试解决挑战练习。我有一个简单的 JSON 数组存储在一个端口(节点)上,我使用 fetch API 将它调用到我的反应服务器中。该请求似乎通过了,但我无法在我的反应页面上显示 JSON 对象的任何元素。
我试过研究这个问题,但似乎没有什么是我正在寻找的。
这是主应用程序页面,它向托管在端口 5555 (/list) 上的节点服务器发出 get 请求,其中包含 JSON 元素。
class App extends Component {
constructor(props){
super(props);
this.state = {
cartList: []
};
}
componentDidMount(){
fetch("http://localhost:5555/list").then(data =>
data.json()).then(data => this.setState({cartList:
data})).catch(err => console.log(err));
}
render() {
return (
<div className="Cart-App">
<header className="App-header">
<h1 className="App-title">Welcome to Shopping-
R-US!</h1>
<Cart cartList = {this.state.cartList}/>
</header>
</div>
);
}
}
export default App;
这是我试图显示元素的类,我使用 map 函数遍历数组,并显示我想要的 JSON 对象的特定属性。
class Cart extends Component {
render() {
const products = this.props.cartList.map(product => (
<div className = "col-md-4">
<p>
{product.name}
{product.description}
{product.cost}
</p>
</div>
))
return (
<div className = "products">
<header className="Cart-Header">
<h1 className="App-title">Select which items you want from the catalog below!</h1>
</header>
<p className="Cart-Products">
{products}
</p>
</div>
);
}
}
export default Cart;
这里的目标是仅将数组的元素(或至少特定属性)显示到页眉下的页面上。
解决方案
推荐阅读
- reactjs - 来自 GitHub 的 React 应用程序在 Codepipeline 中的部署失败
- angular - 用户进行身份验证时路由无法正常工作
- apache-kafka - 我可以自定义融合提供的连接器吗?
- python - 从非结构化文本中提取产品名称
- algorithm - 它是更大的线性时间复杂度吗?
- odoo - 如何根据两个不同的字段获取一个字段的值
- javascript - 无法使用 jquery 隐藏/显示 div 标签
- bash - 将文件描述符输出保存到字符串变量
- javascript - 无法访问 JSON 对象中的字段(字符串化),我正在使用 Quasar / vue.js
- r - 根据其他反应性对象过滤反应性对象,而两者都依赖于第三个反应性对象