【问题标题】:React data pull not working反应数据拉动不起作用
【发布时间】:2016-10-04 23:02:28
【问题描述】:

我是新来的反应并尝试构建一个表格组件,该组件会根据为标题和行传递的内容进行更改。

我一直在关注 fb react 教程,我遇到了一个障碍,我在这里查看并做了一些更改,但没有任何效果。

这是获取生成内容的 HTML 页面。

<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta charset='utf-8'>
        <meta http-equiv="X-UA-Compatible" content="IE=10; IE=9; IE=8; IE=7; IE=EDGE" />
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
        <link rel="stylesheet" type="text/css" href="/vendor/twbs/bootstrap/dist/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="/vendor/etdsolutions/sweetalert/sweetalert.css?<?= assetCacheQueryStr() ?>" />
        <link rel="stylesheet" type="text/css" href="/lib/jquery-ui-1.11.4/jquery-ui.css">
        <link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.9.3/css/bootstrap-select.min.css">

        <!-- Javascript -->
        <script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
    <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
    <script src="https://unpkg.com/jquery@3.1.0/dist/jquery.min.js"></script>
    <script src="https://unpkg.com/remarkable@1.6.2/dist/remarkable.min.js"></script>
        <script src="/vendor/etdsolutions/sweetalert/sweetalert.min.js?<?= assetCacheQueryStr()?>"></script>
    <script src="/vendor/twbs/bootstrap/dist/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.9.3/js/bootstrap-select.min.js"></script>
        <script src="/lib/sorttable.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>

    <title>React</title>
  </head>
    <body>
        <div id="loadboardContainer"></div>

        <!-- Import the table react setup. -->
        <script type="text/babel" src="test.js"></script>
    </body>
</html>

现在我在 test.js 文件中有外部反应脚本,就是这个。

var Table = React.createClass({
  getInitialState: function() {
    return {
      results: [],
      columns: []
    }
  },
  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function(result) {
      result = JSON.parse(result);
      this.setState({
        results: result['resultRows'],
        columns: $.makeArray(result['resultCols'])
      });
    }.bind(this));
  },
  componentWillUnmount: function(){
    this.serverRequest.abort();
  },
  render: function() {
    // Set array for rows.
    var rows = [];
    var header = [];

    this.state.columns.map(function(cols) {
      header.push(<TableColumns data={cols.cols} key={cols.id} />);
    });

    this.state.results.map(function(result) {
      rows.push(<TableRow data={result.rows} key={result.id} />);
    });

    // Loop through head to get columns.
    /*this.props.columns.forEach(function(cols) {
      header.push(<TableColumns data={cols.cols} key={cols.id} />);
    });

    // Loop through the returned rows and display.
    this.props.results.forEach(function(result) {
      rows.push(<TableRow data={result.rows} key={result.id} />);
    });*/


    // Return the table.
    return (
      <table className="table table-condensed">
        <thead>
          {header}
        </thead>
        <tbody>
          {rows}
        </tbody>
      </table>
    );
  }
});

// Set up columns
var TableColumns = React.createClass({
  render: function() {
    var colNodes = this.props.data.map(function(col, i){
      return (
        <th key={i}>{col}</th>
      );
    });
    return (
      <tr>
        {colNodes}
      </tr>
    );
  }
});

// Set up row
var TableRow = React.createClass({
  render: function() {
    var rowNodes = this.props.data.map(function(row, i){
      return (
        <td key={i}>{row}</td>
      );
    });
    return (
      <tr>
        {rowNodes}
      </tr>
    );
  }
});

var futureContainer = document.getElementById('loadboardContainer');

ReactDOM.render(<Table source="getTableValues.php" />, futureContainer);

如您所见,我已将以前的道具调用部分注释掉。现在我正在尝试从另一个文件中获取信息,它看起来像在这里我必须使用状态。

在另一个文件中,这是我所拥有的。它只是一个数组数组,用于在我实际查询内容之前返回数据。

<?php
  // Start the session.
  session_start();

  // Set Variables.
  $returned = array(); // Returns results

  $returned['resultRows'][0] = array();
  $returned['resultRows'][0]['id'] = 10221;
  $returned['resultRows'][0]['rows'] = array("654221", "2016-03-26", "Customer 1", "98755/54622", "Carrier 1", "Driver 1", "2016-03-28", "TX - IN", "DRY", "1240", "", "", "This is a test note");

  $returned['resultRows'][1] = array();
  $returned['resultRows'][1]['id'] = 10223;
  $returned['resultRows'][1]['rows'] = array("654221", "2016-03-26", "Customer 1", "98755/54622", "Carrier 2", "Driver 2", "2016-03-28", "TX - IN", "DRY", "1240", "", "", "This is a test note2");

  $returned['resultCols']['id'] = 100;
  $returned['resultCols']['cols'] = array("PO Number", "Load Date", "Customer(s)", "Customer PO", "Carrier", "Driver", "Delivery Date", "Lane", "Temp", "Weight", "Attention Date", "ND Date", "Notes");

  echo json_encode($returned);
?>

我不断收到错误 this.state.columns.map is not a function。 如果我使用 this.props 也是如此。那么我在这方面做错了什么?如果我静态地放入数据并在自页面上以这种方式插入但调用不起作用,我知道如何使其工作。

【问题讨论】:

  • 在尝试映射之前,您应该检查 this.state.columns 是否未定义。
  • 不应该一直定义它,因为它在getInitialState中设置?如果我提醒它,它只会显示一个空框,但他们的文档说话的方式似乎很长,并且它在定义的 getInitialState 中定义。
  • 不要使用警报来测试代码,因为可能会阻塞,请改用console.log。在你改变它之前你有字符串(它们的原型上没有地图)。

标签: javascript php html reactjs


【解决方案1】:

由于 async $.get,您尝试在开头映射一个字符串

替换这个:

getInitialState: function() {
  return {
     results: '',
     columns: ''
  }
}

通过这个:

getInitialState: function() {
  return {
     results: [],
     columns: []
  }
}

编辑以匹配 PHP 返回

var Table = React.createClass({
  getInitialState: function() {
    return {
      results: [],
      columns: []
    }
  },
  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function(result) {
      result = JSON.parse(result);
      this.setState({
        results: result['resultRows'],
        columns: result['resultCols'].cols
      });
    }.bind(this));
  },
  componentWillUnmount: function(){
    this.serverRequest.abort();
  },
  render: function() {    

    // Return the table.
    return (
      <table className="table table-condensed">
        <thead>
          <TableColumns data={this.state.columns} />
        </thead>
        <tbody>
          {this.state.results.map(function(result) {
            rows.push(<TableRow data={result.rows} key={result.id} />);
          })}
        </tbody>
      </table>
    );
  }
});

// Set up columns
var TableColumns = React.createClass({
  render: function() {
    var colNodes = this.props.data.map(function(col, i){
      return (
        <th key={i}>{col}</th>
      );
    });
    return (
      <tr>
        {colNodes}
      </tr>
    );
  }
});

// Set up row
var TableRow = React.createClass({
  render: function() {
    var rowNodes = this.props.data.map(function(row, i){
      return (
        <td key={i}>{row}</td>
      );
    });
    return (
      <tr>
        {rowNodes}
      </tr>
    );
  }
});

var futureContainer = document.getElementById('loadboardContainer');

ReactDOM.render(<Table source="getTableValues.php" />, futureContainer);

【讨论】:

  • 哦,那么反应不会覆盖变量吗?我现在改了,说状态是未定义的。
  • React 将覆盖变量,但在您的请求完成之后。所以在他尝试映射一个字符串之前。但是为什么这个状态是未定义的? ...您可以记录结果(在 $.get 中)然后是状态(在 render() 中)吗?
  • {"resultRows":[{"id":10221,"rows":["654221","2016-03-26","客户 1","98755\/54622", "Carrier 1","Driver 1","2016-03-28","TX - IN","DRY","1240","","","这是测试说明"]},{" id":10223,"rows":["654221","2016-03-26","Customer 1","98755\/54622","Carrier 2","Driver 2","2016-03-28 ","TX - IN","DRY","1240","","","这是一个测试 note2"]}],"resultCols":{"id":100,"cols":[" PO 编号","装载日期","客户","客户 PO","承运人","司机","交货日期","车道","温度","重量","注意日期" ,"ND 日期","备注"]}}
  • 我不敢相信this.state是未定义的......这真的很奇怪......
  • 是的,我只是放入了一个 json.parse,它会像我想的那样返回对象,但之后它告诉我 this.state.columns.map 不是一个函数跨度>
猜你喜欢
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2012-12-20
  • 1970-01-01
  • 2017-06-20
相关资源
最近更新 更多