如何使用ReactJs将JSON数据显示为表格

8
我想在表格中使用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

请查看此链接,这里有你需要的一切:https://www.npmjs.com/package/react-table - TariqN
2个回答

14

您可以使用 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调用,然后获取数据,将其保存在状态中,然后执行相同的操作即可。我展示的是一个演示,其中我复制了状态中的数据。 - Shubham Khatri
我尝试过了,但是出现了这个错误:XMLHttpRequest 无法加载 http://127.0.0.1:8000/assurance/?format=json。所请求的资源中没有 'Access-Control-Allow-Origin' 标头。因此,来源为 'null' 的访问被拒绝。我无法访问这个链接。 - Mamoudou Ndiaye
它会给你这个错误,因为你需要在服务器上启用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,您将得到答案。 - Shubham Khatri
我不使用Node.js,而是使用django_restframework,所以我会搜索如何启用CORS。谢谢帮助。 - Mamoudou Ndiaye
我使用Chrome浏览器的“cors extension”扩展程序找到了解决方案。 - Mamoudou Ndiaye
显示剩余4条评论

8
如果您想展示数据的组件,可以采用以下方式:
<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'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接