如何使用 Rails 和 React 获取工作 Fetch API。
设置:来自 Webpacker 的 Rails 5、Sprockets 和 React。
我在这里想要实现的是使用 Fetch API 来获取数据并将其加载到 ReactBootstrapTable API。
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import 'whatwg-fetch'
class ExampleTable extends React.Component {
constructor() {
super();
this.state = {
datatable: [], // I'm not sure if I can use array to json data.
};
}
// I'm new to React, so I'm not sure if I'm passing props right
componentDidMount() {
console.log('start componentDidMount');
fetch('https://www.test.com/test.json')
.then(function(response) {
return response.json();
}).then(function(response) {
let datatable = response;
this.setStates({ datatable });
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
render() {
return (
<div>
<BootstrapTable
data={this.states.datatable} //Here, I'm passing data to the table
pagination
striped hover condensed
options={ { noDataText: 'Empty Table' } }>
<TableHeaderColumn isKey dataField='id' width='80px' dataAlign='center'>
ID
</TableHeaderColumn>
<TableHeaderColumn dataField='test'width='300px' dataAlign='left'>
Test
</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
export default ExampleTable;
这里的主要问题是我无法使用 Fetch API,而且我也不完全确定我将数据传递给表的方式(基本上如何使用反应)
我的 IDE 收到错误/警告
fetch 未定义
来自 Firefox 控制台的另一条错误消息:
上述错误发生在组件中:在ExampleTable中
类型错误:this.states 未定义
我通过 yarn 安装了 Fetch API 并检查了 node_modules/whatwg-fetch 文件夹。如 github API 所述,我导入了“whatwg-fetch”,如上面的代码所示。
我不知道我还应该做什么。我以同样的方式安装了 ReactBoostrapTable 并且成功了。其他一切工作正常。