在reactJS中从json响应创建动态表

时间:2016-07-22 23:02:58

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

我是新手以及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'}

感谢。

2 个答案:

答案 0 :(得分:1)

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

更新:

使用最新的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>
   ) 
 }

答案 1 :(得分:1)

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

我确实想把这个家伙归功于他指向正确方向的jsfiddle:http://jsfiddle.net/jhudson8/dahdx6eu/

虽然这适用于我,但您必须先做一些事情。 1.根据React iterate over object from json data中的说明创建一个状态,我称之为加载并在我的初始状态下将其设置为true。 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>
      );
    },
});