【问题标题】:Fetch API not working with Rails + React from WebpackerWebpacker 中的 Fetch API 无法与 Rails + React 一起使用
【发布时间】:2017-12-22 03:12:41
【问题描述】:

如何使用 Rails 和 React 获取工作 Fetch API。

设置:Rails 5、Sprockets 和来自 Webpacker 的 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,而且我也不完全确定我将数据传递到表的方式(基本上如何使用 react)

我的 IDE 收到错误/警告

获取未定义

还有来自 Firefox 控制台的另一条错误消息:

上述错误发生在组件中:在ExampleTable中

TypeError: this.states 未定义

我通过 yarn 安装了 Fetch API 并检查了 node_modules/whatwg-fetch 文件夹。如 github API 所述,我导入了上面代码所示的“whatwg-fetch”。

我不知道我还能做什么。我以同样的方式安装了 ReactBoostrapTable 并且成功了。其他一切正常。

【问题讨论】:

    标签: ruby-on-rails reactjs fetch-api webpacker


    【解决方案1】:

    我查看了用于 webpack 的 fetch 的 installation instructions,它说要将此添加到您的 webpack 配置中:

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

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

    this.state.datatable
    

    在您的render 方法中,您引用this.states

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

    this.setState({ somestate: "xyz"})
    

    【讨论】:

    • 感谢您看到错别字!哈哈修复这些在控制台中给了我另一个错误消息,但现在编译似乎到达了 fetch 方法!进步了嘿嘿。关于安装说明,我认为它不起作用,因为我使用的是 Webpacker 而不是 Webpack。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多