开发者问题收集

获取 react-bootstrap-table 的错误消息

2020-04-14
4581

我已经通过 npm 安装了“react-bootstrap-table2”,并且为表格编写了一个示例代码,但是当我运行此代码时,浏览器控制台中出现错误消息

Uncaught TypeError: Cannot read property 'filter' of undefined at new BootstrapTableContainer (index.js:96)

import React, { Component } from 'react';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import BootstrapTable from 'react-bootstrap-table-next';

class UserList extends Component {

  constructor(props) {
    super(props);
    const products = [];
    const columns = [{
        dataField: 'id',
        text: 'Product ID'
      }, {
        dataField: 'name',
        text: 'Product Name'
      }, {
        dataField: 'price',
        text: 'Product Price'
      }];
  }

  render() {
    return (
      <div>
        <BootstrapTable
          keyField='id'
          data={this.products}
          columns={this.columns}
        />
      </div>
    );
  }
}

export default UserList;
2个回答

constructor 中定义类变量时,不是用 const 定义,而是用 on this 定义。

constructor(props) {
  super(props);
  this.products = [];
  this.columns = [{
      dataField: 'id',
      text: 'Product ID'
    }, {
      dataField: 'name',
      text: 'Product Name'
    }, {
      dataField: 'price',
      text: 'Product Price'
    }];
}
Drew Reese
2020-04-14

您尚未在构造函数中为 this.products 分配任何内容

class UserList extends Component {

  constructor(props) {
    super(props);
    // const products = []; 
    this.products = []; // this.products should be assigned some value/array
    const columns = [{
        dataField: 'id',
        text: 'Product ID'
      }, {
        dataField: 'name',
        text: 'Product Name'
      }, {
        dataField: 'price',
        text: 'Product Price'
      }];
  }

  render() {
    return (
      <div>
        <BootstrapTable
          keyField='id'
          data={this.products}
          columns={this.columns}
        />
      </div>
    );
  }
}

这可能有效,但不是一个好方法。数据应处于状态变量中,因此当您更新状态时,您的组件将被重新渲染并且将显示新的更改,否则更新 this.products 将不会触发重新渲染,并且组件将显示过时的数据。

class UserList extends Component {

  constructor(props) {
    super(props);
    // const products = [];
    this.state = { products: [] };
    const columns = [{
        dataField: 'id',
        text: 'Product ID'
      }, {
        dataField: 'name',
        text: 'Product Name'
      }, {
        dataField: 'price',
        text: 'Product Price'
      }];
  }
  
  componentDidMount = async () => {
    // Get data from some api and then update the state
    const res = await fetch('/some url');
    const products = await res.json();
    this.setState({ products });
  }

  render() {
    return (
      <div>
        <BootstrapTable
          keyField='id'
          data={this.products}
          columns={this.columns}
        />
      </div>
    );
  }
}
Zohaib Ijaz
2020-04-14