首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sortBy函数中的错误是什么

sortBy函数中的错误是什么
EN

Stack Overflow用户
提问于 2018-03-20 17:20:05
回答 1查看 965关注 0票数 0

我刚接触react,在react中对json对象中的数据表进行排序时遇到了问题。我已经正确地呈现了数据表,但是当我尝试在单元组件上使用onClick对数据表进行排序时,错误显示“./src/App.jsLine 34:'tableData‘is not defined no-undef”。

请指出I am making.The源代码的错误是什么:

代码语言:javascript
复制
  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;
EN

回答 1

Stack Overflow用户

发布于 2018-03-20 17:31:59

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

代码语言:javascript
复制
sortBy(sort_attr) {
  const {tableData} = this.state;
  this.setState({
      tableData: tableData.sort('ascending')
      });
  }

但是,由于您是基于prevState更新currentState的,因此应该使用如下所示的functional setState

代码语言:javascript
复制
sortBy(sort_attr) {
  this.setState(prevState => ({
      tableData: prevState.tableData.sort('ascending')
      }));
  }

有关when to use functional setState的更多信息,请查看此问题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49380319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档