javascript - 显示获取请求中的元素

标签 javascript node.js reactjs

我目前正在尝试学习React,并试图解决挑战练习。我在端口(节点)上存储了一个简单的JSON数组,使用提取API将其调用到我的react服务器中。该请求似乎已通过,但是我无法在我的react页面上显示JSON对象的任何元素。

我曾尝试研究此问题,但似乎并非我要找的东西。

这是App主页面,它向包含JSON元素的端口5555(/ list)上托管的Node服务器发出get请求。

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;


此处的目标是仅将数组的元素(或至少特定属性)显示在标题下的页面上。

最佳答案

如果使用fetch从API获取json数据,则需要通过调用data.json()将响应数据对象转换为json(返回诺言)。

看一下它在您的App组件中的正确用法:

  componentDidMount() {
    fetch("http://localhost:5555/list")
      .then(data => data.json())
      .then(data =>
        this.setState({
          cartList: data
        })
      )
      .catch(err => console.log("Error:", err));
  }


请注意,.then().catch()都将函数作为参数!

您可以在这里工作:https://codesandbox.io/s/react-fetch-data-qeuwf?fontsize=14

关于javascript - 显示获取请求中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471792/

相关文章:

javascript - 使用变量创建动态 meteor 集合

mysql - TypeORM Querybuilder 获取嵌套 INNER JOIN

python - NodeJS 和 Python 哈希的区别

javascript - 模块化和抽象 react 组件功能

javascript - 在显示将来可能会更改的选择选项列表时,我应该在 UI 中对它们进行硬编码还是从我的数据库中获取?

javascript - 我可以添加交互性 (JS/CSS) 来影响 Bodymovin/Lottie 动画中的元素吗?

javascript - Node.js 中的调用函数

javascript - 为什么每次刷新logo我的页面都会自动上去?

Node.js - 使用查询字符串以 GET/POST 形式发送和接收数组

javascript - 我跟随文档自定义主题时使用弹性ui时遇到问题