为数据表的所有列构造状态对象以进行排序:React JS [英] Constructing state object for all the columns of a data table for sorting : React JS

查看:62
本文介绍了为数据表的所有列构造状态对象以进行排序:React JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要构造一个状态对象,该对象将有助于维护字段名和排序类型(升序/降序).

Need to construct a state object that will be helpful for maintaining fieldname and type of sort(ascending/descending).

我正在尝试通过获取列名和排序类型(asc或des)来实现在服务器端进行排序的排序.

I am trying to implement sorting where the sorting on the server side happens by taking the column name and the type of sort(asc or des).

我正在维护数据表的组件,在其中添加了一个单击处理程序,该单击处理程序基本上应提供要单击的字段名称和排序类型.我可以对fieldnam进行硬编码,但是如何将每个列与排序类型进行映射.

I am maintaining a component for a data table where-in I attach a click handler that basically should give the field name that I click and the type of sorting. I can hardcode the fieldnam, But how will I map each column with type of sorting.

我只需要将字段名称和类型发送给后端,然后它将给我排序的结果.如何使用asc/desc

I just need the name of the field and type to be sent to the backend, then it will give me sorted results. How will I map corresponding column names with either asc/desc

有人可以帮我吗?

沙箱: https://codesandbox.io/s/misty-water-iutxl

import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";
import Child from "./Child";
interface IState {
  data: {}[];
  columns: {}[];
  selectedValues: {};
}

interface IProps {}

export default class App extends React.Component<IProps, IState> {

  constructor(props: any) {
    super(props);
    this.state = {
      data: [],
      columns: [],
    };
  }

  componentDidMount()
  {
    this.getColumnFilterValues();
    this.getData();
  }

  getData = () =>{
    let data = [
        { firstName: "Jack", status: "Submitted", age: "14" },
        { firstName: "Simon", status: "Pending", age: "15" },
        { firstName: "Pete", status: "Approved", age: "17" }
      ];
      this.setState({data},()=> this.getColumns());
  }

  getColumnFilterValues = () =>{
    let optionsForColumns = {
        firstName: [
          { Jack: "4", checked: false },
          { Simon: "5", checked: false },
          { Pete: "10", checked: false }
        ],
        status: [
          { Submitted: "5", checked: false },
          { Pending: "7", checked: false },
          { Approved: "15", checked: false }
        ]
      }
      this.setState({optionsForColumns});
  }

  sortHandler = (name) =>{
     //Sort Handler, here I have to pass the field name and type of sorting
  }

  getColumns = () =>{
    let columns = [
      {
        Header: () => (
          <div>
            <div style={{ position: "absolute", marginLeft: "10px" }}>
              <Child
                key="firstName"
                name="firstName"
                options={this.getValuesFromKey("firstName")}
                handleFilter={this.handleFilter}
              />
            </div>
            <span onClick={()=>this.sortHandler("firstName")}>First Name</span>
          </div>
        ),
        accessor: "firstName",
        sortable: false,
        show: true,
        displayValue: " First Name"
      },
      {
        Header: () => (
          <div>
            <div style={{ position: "absolute", marginLeft: "10px" }}>
              <Child
                key="status"
                name="status"
                options={this.getValuesFromKey("status")}
                handleFilter={this.handleFilter}
              />
            </div>
            <span onClick={()=>this.sortHandler("status")}>Status</span>
          </div>
        ),
        accessor: "status",
        sortable: false
      },
      {
        Header: () =>(
          <span onClick={this.sort}>Age</span>
        ),
        accessor: "age"
      }
    ];
    this.setState({ columns });
  }

  //Rendering the data table
  render() {
    const { data, columns } = this.state;
    return (
      <div>
        <ReactTable
          data={data}
          columns={columns}
        />
      </div>
    );
  }
}


推荐答案

排序类型将只是当前排序类型的倒置.因此,您需要跟踪每个列的排序类型.之后,您可以执行类似操作;

The sorting type will be just an inversion of the current sorting type. So you would need to keep track each column sorting type. After that, you can do something like;

// imagine sortingTypes are stored in the state like so:
state = {
  sortingTypes: {
    firstName: 'ASC',
    lastName: '',
  },
};


// in the onClick handler
sortHandler = (name) =>{
  //Sort Handler, here I have to pass the field name and type of sorting

  // Make a new sortingTypes object
  const sortingTypes = Object.keys(this.state.sortingTypes).reduce((obj, key) => {
    if (key === name) {
      obj[key] = sortingTypes[key] === 'ASC' ? 'DESC' : 'ASC';
    } else {
      obj[key] = '';
    }

    return obj;
  }, {});

  // calling this.getColumns() in the setState callback function is not recommended. 
  // The getColumns function is also calling setState and caused the component to update 
  // twice while that is not needed.
  this.setState({ sortingTypes }, () => this.getColumns());
}

修改

查看表之后,我意识到您不必自己管理状态.只需设置manualonFetchData道具,您就知道何时获取数据以及使用哪种排序选项;

After looking into react-table, I've realised that you don't have to manage the state yourself. Just set the manual and onFetchData prop and you know exactly when to fetch your data and with which sorting options;

<ReactTable
  data={data}
  columns={columns}
  defaultPageSize={10}
  loading={this.state.loading}
  className="-striped -highlight"
  onFetchData={(({ sorted }) => {
    // here you can fetch data with the table state like `sorting`.
    console.log(sorted && sorted[0] && sorted[0].id);
  })}
  manual
/>

请参见服务器端数据更多信息,请参见React Table文档中的章节.

See the Server-side data chapter in the React Table documentation for more information.

这篇关于为数据表的所有列构造状态对象以进行排序:React JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆