Build a dynamic table using array data generated from PHP in JSX/React

时间秒杀一切 提交于 2019-12-31 03:40:15

问题


I am trying to build a table dynamically generated from output array of PHP script. I get the below output after componentWillMount is executed. But I am trying to use this data ( first 4 rows are one row ) and build a table. But i am unable to get how to use this array data and convert it to table dynamically. Any inputs are highly appreciated.

2016-08-24 20:24:06
2016-08-24 20:24:06
test01
20
2016-08-19 08:14:25
2016-08-19 08:14:25
test02
10


  componentWillMount: function () {
        $.ajax({
            type: "GET",
            crossDomain: true,
            url: "http://localhost:8080/myscript.php",
            success: function(data){
                alert(data);
                this.setState({testRows: data});
            }.bind(this),
            error:function(data)
            {
                alert("Data sending failed");
            }
        });
    },
 return(
  <tbody>
  {this.state.testRows.map(function(row, i) {
  return (
  <tr key={i}>
  {row.map(function(col, j) {
  return <td key={j}>{col}</td>;
  })}
 </tr>
  );
  })}
 </tbody>
)

回答1:


What I do is that i create a 2-dimensional array which i pass to the List component. If you know that every group of 4 in the array you get from the php script is a row then you just use a for loop like this.(phpResponse is the response from the php script)

var tableData = [];
var tableRow = [];
for(var x = 1; x <= phpResponse.length; x++) {
    tableRow.push(phpResponse[x]);
    if (x % 4 == 0) {
        tableData.push(tableRow);
        tableRow = [];
    }
}

And then you use tableData like this

return(
    <tbody>
         {tableData.map((row, index) => {
             return (
                 <tr key={"row_" + index}>
                     {row.map((cell, index) => {
                         return (
                             <td key={"cell_" + index}>{cell}</td>
                         );
                     })}
                 </tr>
             );
         })}
    </tbody>
);


来源:https://stackoverflow.com/questions/39137647/build-a-dynamic-table-using-array-data-generated-from-php-in-jsx-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!