【问题标题】:How to display json data with ReactJs as table如何使用 ReactJs 将 json 数据显示为表格
【发布时间】:2017-03-13 20:16:44
【问题描述】:

我想用reactJs在表格中显示我的json数据,但是我不能。

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },

...

]

完整源代码:http://jsonplaceholder.typicode.com/posts

【问题讨论】:

标签: json reactjs


【解决方案1】:

您可以使用 map 来遍历您的 JSON 数据

class App extends React.Component {
  constructor(){
    super() 
      this.state = {
        data: []
      }
    
  }
  componentDidMount() {
    $.ajax({
       url: "http://jsonplaceholder.typicode.com/posts",
       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.userId}</td>
                      <td>{item.id}</td>
                      <td>{item.title}</td>
                      <td>{item.body}</td>
                  </tr>
                )
             
             })}</tbody>
       </table>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>

【讨论】:

  • 从外部链接获取JSON数据不是问题。您只需要调用 ajax 并获取数据,将其保存在状态中,然后执行相同操作。我展示的是一个演示,我在该演示中复制了 state 中的数据。
  • 我试过了,但是我有这个错误:XMLHttpRequest cannot load 127.0.0.1:8000/assurance/?format=json。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。我无法访问此链接
  • 您是否尝试从您发布的有问题的同一个 api 加载数据。我认为它不支持CORS。让我检查一下
  • 谢谢,它的工作,但我尝试用本地链接替换链接(127.0.0.1:8080/assurance/?format=json)我有这个错误:XMLHttpRequest 无法加载 127.0.0.1 :8000/保证/?格式=json。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。我无法访问此链接。
  • 它会给你这个错误,因为你需要在你的服务器中启用 CORS。如果您使用的是 Node.js 服务器,则将 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); 添加到您的服务器代码中。如果使用其他搜索如何启用 CORS,您将得到答案。
【解决方案2】:

你的目标是让组件显示数据吗,你可以这样做

<div id="example"></div>

var cols = [
    { key: 'id', label: 'Id' },
    { key: 'userId', label: 'User' },    
    { key: 'title', label: 'Title' },
    { key: 'body', label: 'Body' }
];

var data = [
  {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
];

var Table = React.createClass({

render: function() {
    var headerComponents = this.generateHeaders(),
        rowComponents = this.generateRows();

    return (
        <table>
            <thead> {headerComponents} </thead>
            <tbody> {rowComponents} </tbody>
        </table>
    );
},

generateHeaders: function() {
    var cols = this.props.cols;  // [{key, label}]

    // generate our header (th) cell components
    return cols.map(function(colData) {
        return <th key={colData.key}> {colData.label} </th>;
    });
},

generateRows: function() {
    var cols = this.props.cols,  // [{key, label}]
        data = this.props.data;

    return data.map(function(item) {
        // handle the column data within each row
        var cells = cols.map(function(colData) {

            // colData.key might be "firstName"
            return <td> {item[colData.key]} </td>;
        });
        return <tr key={item.id}> {cells} </tr>;
    });
}
});

React.render(<Table cols={cols} data={data}/>,  document.getElementById('example'));

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 1970-01-01
    • 2020-05-24
    • 2018-10-13
    • 2016-04-20
    • 2021-11-27
    • 2013-07-08
    • 1970-01-01
    • 2015-08-23
    相关资源
    最近更新 更多