【问题标题】:What is the error in sortBy functionsortBy 函数的错误是什么
【发布时间】:2018-08-29 00:53:55
【问题描述】:

我是新来的反应,并且在从 json 对象重新生成的反应中对数据表进行排序时遇到问题。 我已经正确渲染了数据表,但是当我尝试在单元格组件上使用 onClick 对数据表进行排序时,错误提示 "./src/App.js 第 34 行:'tableData' 未定义 no-undef"。

请指出我犯了什么错误。源代码是:

  import React from 'react';
  import axios from 'axios';
  import {Table, Column, Cell} from 'fixed-data-table-2';
  import 'fixed-data-table-2/dist/fixed-data-table.css';

  class App extends React.Component {
    constructor (props) {
      super(props);
      this.state = { tableData : []};
      this.sortBy = this.sortBy.bind(this);
    }

    sortBy(sort_attr) {
      this.setState({
          tableData: tableData.sort('ascending')
          });
      }


  componentDidMount() {
      axios.get('https://drupal8.sample.com/my-api/get.json', {
            responseType: 'json'
        }).then(response => {
            this.setState({ tableData: response.data });
            console.log(this.state.tableData);
        });
      }


    render() {
      const rows = this.state.tableData;
      return (
        <Table
        rowHeight={50}
        rowsCount={rows.length}
        width={500}
        height={500}
        headerHeight={50}>
        <Column
      header={<Cell onClick= {this.sortBy}>resourceID</Cell>}
      columnKey="resourceID"
      cell={({ rowIndex, columnKey, ...props }) =>
        <Cell {...props}>
          {rows[rowIndex][columnKey]}
        </Cell>}
      width={200}
    />
      <Column
      header={<Cell>resourceType</Cell>}
      columnKey="resourceType"
      cell={({ rowIndex, columnKey, ...props }) =>
        <Cell {...props}>
          {rows[rowIndex][columnKey]}
        </Cell>}
      width={200}
    />
        <Column
      header={<Cell>tenantName</Cell>}
      columnKey="tenantName"
      cell={({ rowIndex, columnKey, ...props }) =>
        <Cell {...props}>
          {rows[rowIndex][columnKey]}
        </Cell>}
      width={200}
    />
      </Table>
      );
    }
  }

  export default App;

【问题讨论】:

    标签: reactjs sorting fixed-data-table


    【解决方案1】:

    在您的 sortBy 函数中,您正在使用 tableData 而不会从状态中解构它

    sortBy(sort_attr) {
      const {tableData} = this.state;
      this.setState({
          tableData: tableData.sort('ascending')
          });
      }
    

    不过既然你是在prevState的基础上更新currentState,你应该像functional setState一样使用

    sortBy(sort_attr) {
      this.setState(prevState => ({
          tableData: prevState.tableData.sort('ascending')
          }));
      }
    

    查看此问题以获取有关 when to use functional setState 的更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 2016-09-19
      • 2023-02-21
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      相关资源
      最近更新 更多