【问题标题】:How to make the API call and display it in React JS using React Table and Axios?如何使用 React Table 和 Axios 进行 API 调用并将其显示在 React JS 中?
【发布时间】:2018-02-08 01:07:03
【问题描述】:

我是 React 新手,我必须从 API 获取数据并将其显示在表格中。我使用 React Table 来显示表中的数据。如何实现上述内容?目前我在 Google chrome 开发控制台中没有看到来自服务器的任何响应。 React Table 实现使用本地数据工作,但是从 API 填充表不起作用。 我的代码如下:

    class TableExp extends React.Component {
     constructor() {
     super();

  this.state = {
      tableData: {
        resourceID: '',
        resourceType: '',
        tenantName: '',
        dealerID: '',
        status: '',
        logFilePath: '',
        supportPerson: '',
        lastUpdatedTime: '',
      },
  };
}

 componentDidMount() {
    axios.get(`https://myAPI.restdb.io/rest/mock-data`, {
    headers: {'x-apikey': 'apiKEY'}
  })
.then(response => {
      this.setState({ tableData: response.data.tableData });
      //console.log(tableData);
});}

  render() {
  const { tableData } = this.state;

  return (
      <div>
       <ReactTable
            data={tableData}
            columns={[
              {
                Header: 'Details',
                columns: [
                  {
                    Header: 'Tenant Name',
                    accessor: '{this.state.tableData.tenantName}',
                  },
                  {
                    Header: 'Support Engineer',
                    id: '{this.state.tableData.supportEngineer}',
                    accessor: d => d.supportPerson,
                  },
                ],
              },
              {
                Header: 'Info',
                columns: [
                        {
                          Header: 'Dealer ID',
                          accessor:'{this.state.tableData.dealerID}',
                        },
                        {
                          Header: 'Status',
                          accessor:'{this.state.tableData.status}',
                        },
                      ],
              },
              {
                Header: 'Logs',
                columns: [
                        {
                          Header: 'File Path',
                          accessor:'{this.state.tableData.filePath}',
                        },
                      ],
              },
            ]}
            defaultPageSize={10}
            className="-striped -highlight"
        />
     </div>
    );
}
   }

   export default TableExp;

【问题讨论】:

  • 当你console.log(response)时它会记录什么?
  • >app.js:139699 未捕获的错误:模块构建失败:SyntaxError:相邻的 JSX 元素必须包含在封闭标记中 (100:8) >/src/components/dashboard/tableSupport/tableExp. js Module build failed: SyntaxError: Adjacent JSX elements must be Wrap in an enclosure tag (100:8)
  • @SeaWarrior404,console.log(response),而不是console.log(tableData);
  • 是的,我编辑了 console.log(tableData) 并用 console.log(response) 更新了它,这是响应 app.js:139699 Uncaught Error: Module build failed: SyntaxError: Adjacent JSX元素必须包含在封闭标记中 (100:8) >/src/components/dashboard/tableSupport/tableExp.js 模块构建失败:SyntaxError: Adjacent JSX 元素必须包含在封闭标记中 (100:8)
  • tableExp.js 文件的第 100 行是什么?您发布的代码没有 100 行。

标签: javascript reactjs axios


【解决方案1】:
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width-device-width, initial-scale-1">
    <script src="http://www.jimsproch.com/react/future/react.js"></script>
    <script src="http://www.jimsproch.com/react/future/react-dom.js"></script>
    <script src="http://www.jimsproch.com/react/babel-browser.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.5.3/react-table.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.5.3/react-table.css">
</head>
<body>
<div id="root"></div>
<script type="text/babel">
    class TableExp extends React.Component {
        constructor () {
            super();

            this.state = {
                tableData: [{
                    resourceID: '',
                    resourceType: '',
                    tenantName: '',
                    dealerID: '',
                    status: '',
                    logFilePath: '',
                    supportPerson: '',
                    lastUpdatedTime: '',
                }],
            };
        }

        componentDidMount () {
            axios.get('http://private-9ff5e-stackoverflow.apiary-mock.com/questions', {
                responseType: 'json'
            }).then(response => {
                this.setState({ tableData: response.data });
            });
        }

        render () {
            const { tableData } = this.state;

            return (<ReactTable.default
                            data={tableData}
                            columns={[
                                {
                                    Header: 'Details',
                                    columns: [
                                        {
                                            Header: 'Tenant Name',
                                            accessor: 'tenantName',
                                        },
                                        {
                                            Header: 'Support Engineer',
                                            id: 'supportEngineer',
                                            accessor: d => d.supportPerson,
                                        },
                                    ],
                                },
                                {
                                    Header: 'Info',
                                    columns: [
                                        {
                                            Header: 'Dealer ID',
                                            accessor: 'dealerID',
                                        },
                                        {
                                            Header: 'Status',
                                            accessor: 'status',
                                        },
                                    ],
                                },
                                {
                                    Header: 'Logs',
                                    columns: [
                                        {
                                            Header: 'File Path',
                                            accessor: 'logFilePath',
                                        },
                                    ],
                                },
                            ]}
                            defaultPageSize={10}
                            className="-striped -highlight"
                    />
            );
        }
    };

    ReactDOM.render(<div><TableExp/></div>, document.getElementById("root"));
</script>
</body>
</html>

有适合​​你的解决方案:link to jsbin

我为您的示例制作了我使用的模拟 api。你可以查看here

关于我所做的修复的几句话:

  • ReactTable 中的属性“数据”更改为数组
  • 固定访问器值(检查documentation

不要关注ReactTable.default(浏览器环境示例需要)

【讨论】:

  • 像魅力一样工作!非常详尽的回答,谢谢!
  • 如何在表格中显示序列号。请注意,序列号不在 JSON 中。请任何人都可以帮助我
猜你喜欢
  • 1970-01-01
  • 2017-07-18
  • 2020-08-25
  • 2020-12-15
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2019-09-15
  • 2017-10-28
相关资源
最近更新 更多