javascript 如何使用 React Table 和 Axios 进行 API 调用并在 React JS 中显示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45958356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:20:43  来源:igfitidea点击:

How to make the API call and display it in React JS using React Table and Axios?

javascriptreactjsaxios

提问by SeaWarrior404

Im new to React and I have to fetch data from an API and show it in a table. Im using the React Table for displaying the data in the table. How to implement the above? Currently Im not seeing any response from the server in the Google chrome dev console. The React Table implementation works using local data, however populating the table from an API is not working. My code is as follows:

我是 React 的新手,我必须从 API 获取数据并将其显示在表格中。我使用 React Table 来显示表格中的数据。如何实现以上内容?目前我在谷歌浏览器开发控制台中没有看到来自服务器的任何响应。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;

回答by chuve

<!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>

There is solution for you: link to jsbin

有你的解决方案:链接到jsbin

I have made mock api for your example, that I used. You can check it here

我为您的示例制作了模拟 api,我使用过。你可以在这里查看

Few words about fixes that I made:

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

  • property "data" in ReactTable changed to an array
  • fixed accessors values (check documentation)
  • ReactTable 中的属性“data”更改为数组
  • 固定访问器值(检查文档

Do not pay attention on ReactTable.default (it is necessary for browser env example)

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