首页 > 解决方案 > 如何在我的 HTML 页面上使用 reactjs 显示此 json 数据

问题描述

我对网页设计非常陌生(实际上没有先验知识),目前正在尝试创建一个网站,该网站使用 Nodejs 从我的 MySQL 数据库中提取数据并使用 Reactjs 将其显示在我的 HTML 页面上。任何帮助将不胜感激

我之前复制了如何在表中使用 ReactJs 显示 json 数据的代码,但是当我使用来自本地主机服务器的 URL 和其中的 JSON 数据时,它只显示错误“TypeError: this.state.data.map is不是函数”。

这是我的 app.js

class App extends React.Component {
    constructor(){
      super() 
        this.state = {
          data: []
        }

    }
    componentDidMount() {
      $.ajax({
         url: "http://localhost:4000/stockin",
         type: "GET",
         dataType: 'json',
         ContentType: 'application/json',
         success: function(data) {

           this.setState({data: data});
         }.bind(this),
         error: function(jqXHR) {
           console.log(jqXHR);
         }.bind(this)
      })
    }
    render() {


      return (
        <table>
        <tbody>{this.state.data.map(function(item, key) {

                 return (
                    <tr key = {key}>
                        <td>{item.No}</td>
                        <td>{item.Stocktype}</td>
                        <td>{item.Binid}</td>
                        <td>{item.Stockid}</td>
                    </tr>
                  )

               })}</tbody>
         </table>
      )
    }
  }

  ReactDOM.render(<App/>, document.getElementById('app'))

这是我的 json 数据

{"stockin":[{"No":1,"Stocktype":"XM21","Binid":"1234124","Stockid":"135215215","Datestockin":"2019-05-05T16:00:00.000Z","Quantity":52,"Remarks":"Good stock"},
{"No":2,"Stocktype":"XM22","Binid":"2352342","Stockid":"123456721","Datestockin":"2019-05-05T16:00:00.000Z","Quantity":21,"Remarks":"Good stock"},
{"No":3,"Stocktype":"screw","Binid":"2432342","Stockid":"123456721","Datestockin":"2019-05-05T16:00:00.000Z","Quantity":23,"Remarks":"Good stock"},
{"No":4,"Stocktype":"screw","Binid":"1325123","Stockid":"242353223","Datestockin":"2019-04-30T16:00:00.000Z","Quantity":32,"Remarks":"Screws for bins"}]}

我希望最终能够在我的 HTML 网站上以表格形式显示数据。

标签: htmlnode.jsjsonreactjs

解决方案


可能是问题最初是数据是空的,所以你必须检查data类似的长度

{this.state.data.length  == 0 && <div>No data found</div>} 
{this.state.data.length > 0 && 
 <table>
    <tbody>{this.state.data.map(function(item, key) {

             return (
                <tr key = {key}>
                    <td>{item.No}</td>
                    <td>{item.Stocktype}</td>
                    <td>{item.Binid}</td>
                    <td>{item.Stockid}</td>
                </tr>
              )

           })}</tbody>
     </table>
  }

推荐阅读