2

如何使用 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 并且成功了。其他一切工作正常。

4

1 回答 1

1

我查看了用于 webpack 的 fetch的安装说明,它说将其添加到您的 webpack 配置中:

entry: ['whatwg-fetch', ...]

另外,您提到了另一个错误TypeError: this.states is undefined。看起来你有一个错字。在 React 中,如果你试图引用状态,你可以像这样使用它:

this.state.datatable

在您的render方法中,您指的是this.states.

此外,当您使用 fetch 拨打电话时,您正在尝试拨打this.setStates. 您应该像这样使用它:

this.setState({ somestate: "xyz"})
于 2017-12-21T19:00:09.150 回答