【问题标题】:Creating a dynamic table from json response in reactJS在 reactJS 中从 json 响应创建动态表
【发布时间】:2016-11-26 22:40:43
【问题描述】:

我是新来的反应以及 UI,我想根据从我的 ajax 调用服务器收到的 JSON 响应创建一个漂亮的表。我该怎么做。

任何类型的信息都会很有帮助。

var Contact = React.createClass({
getInitialState: function(){
  return {}
},

submit: function (e){
  var self

  e.preventDefault()
  self = this

  console.log(this.state);

  var data = {
    Id: this.state.name,
    User: this.state.email,

  }

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'http://localhost:8080/ui/start',
    data: JSON.stringify({
      Id: this.state.name,
      User: this.state.email,
    })
  })
  .done(function(response) {
  console.log(response);

  // This is where I have the JSON response .How can I create a dynamic table from this response **strong text**and render in on UI.  //
 } 

我的回复看起来像这样 {'name':'divya','id':'1','task':'xyz'}

谢谢。

【问题讨论】:

    标签: javascript reactjs react-native react-jsx reactjs-flux


    【解决方案1】:

    我是 React 新手,但正在寻找相同的东西,我希望这可以帮助其他人更快地获得他们需要的结果。我花了一整天的时间寻找这样可行的方法。

    我确实想感谢这个人的 jsfiddle 为我指明了正确的方向:http://jsfiddle.net/jhudson8/dahdx6eu/

    虽然这对我有用,但您必须先做几件事。 1. 创建一个状态,我称之为加载,并按照以下说明在获取初始状态时将其设置为 true:React iterate over object from json data。 2. 我确信这段代码可以使用粗箭头函数等进行一些清理。它无论如何都不完美。

    var GeneralTable = React.createClass({
    
        generateRows: function() {
          if (this.props.loading === false) {
            var cols = Object.keys(this.props.books[0]), data = this.props.books;
            return data.map(function(item) {
                var cells = cols.map(function(colData) {
                    return <td> {item[colData]} </td>;
                });
                return <tr key={item.id}> {cells} </tr>;
            });
          }
        },
        render: function() {
          let rowComponents = this.generateRows();
          let table_rows = []
          let table_headers = [];
          let data = this.props.books;
    
          if (this.props.loading === false) {
            let headers = Object.keys(this.props.books[0]);
            headers.forEach(header => table_headers.push(<th key={header}>{header}</th>));
            data.forEach(book => table_rows.push(<BookTableRow key={book.id} book={book} />));
          }
          return (
              <Table striped bordered>
                  <thead><tr>{table_headers}</tr></thead>
                  <tbody> {rowComponents} </tbody>
              </Table>
          );
        },
    });
    

    【讨论】:

      【解决方案2】:

      将响应存储在状态数组中,并将数据动态映射到表中。

      更新:

      使用最新的 ES6 语法,它可以像这样完成

      class Contact extends React.Component{
          state = {
                personData: []
            }
      
          submit = (e) => {
      
            e.preventDefault()
      
            console.log(this.state);
      
            var data = {
              Id: this.state.name,
              User: this.state.email,
      
            }
      
            $.ajax({
              type: 'POST',
              dataType: 'json',
              url: 'http://localhost:8080/ui/start',
              data: JSON.stringify({
                Id: this.state.name,
                User: this.state.email,
              })
            })
            .done((response) => {
            console.log(response);
            this.state.userData.push({'name': response.name, 'id': response.id, 'task': response.task});
            this.setState({userData: self.state.userData});
      
            // This is where I have the JSON response .How can I create a dynamic table from this response **strong text**and render in on UI.  //
           } 
           render() {
             return(
               <table>
                 <thead>
                    <tr>
                       <th>Name</th>
                       <th>ID</th>
                       <th>Task</th>
                    </tr>
                 </thead>
                 <tbody>
                 {this.state.userData.map((data, key) => {
                    return (
                    <tr key={key}>
                      <td>{data.name}</td>
                      <td>{data.id}</td>
                      <td>{data.task}</td>
                    </tr>
                    )
                 })}
                 </tbody>
               </table>
             ) 
           }
      

      下面有一个例子。

      var Contact = React.createClass({
      getInitialState: function(){
        return {
            personData: []
        }
      },
      
      submit: function (e){
        var self
      
        e.preventDefault()
        self = this
      
        console.log(this.state);
      
        var data = {
          Id: this.state.name,
          User: this.state.email,
      
        }
      
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: 'http://localhost:8080/ui/start',
          data: JSON.stringify({
            Id: this.state.name,
            User: this.state.email,
          })
        })
        .done(function(response) {
        console.log(response);
        self.state.userData.push({'name': response.name, 'id': response.id, 'task': response.task});
        self.setState({userData: self.state.userData});
      
        // This is where I have the JSON response .How can I create a dynamic table from this response **strong text**and render in on UI.  //
       } 
       render() {
         return(
           <table>
             <thead>
                <tr>
                   <th>Name</th>
                   <th>ID</th>
                   <th>Task</th>
                </tr>
             </thead>
             <tbody>
             {this.state.userData.map((data, key) => {
                return (
                <tr key={key}>
                  <td>{data.name}</td>
                  <td>{data.id}</td>
                  <td>{data.task}</td>
                </tr>
                )
             })}
             </tbody>
           </table>
         ) 
       }
      

      【讨论】:

        猜你喜欢
        • 2018-03-14
        • 2017-12-12
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        • 2019-10-10
        • 2016-04-09
        • 2019-01-06
        • 1970-01-01
        相关资源
        最近更新 更多