首页 > 解决方案 > 显示来自 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;

这里的目标是仅将数组的元素(或至少特定属性)显示到页眉下的页面上。

标签: javascriptnode.jsreactjs

解决方案


推荐阅读