简体   繁体   中英

multiple sort table using reactjs

Any clue why this code won't be able to do sorting properly base on columns?

sort(key){
    this.setState({
      [`toggle-${key}`]: !this.state[`toggle-${key}`],
      data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => v)
    })
  } 
  render() {
    return (
      <div style={styles}>
        <table>
          <thead>
            {Object.keys(this.state.data[0]).map(v => {
              return(
                <th onClick={()=>this.sort(v)}>
                  {v.toUpperCase()}
                </th>
              )
              })}
          </thead>
          <tbody>
            {this.state.data.map(v=>{
              return(
                <tr>
                  <td>{v.id}</td>
                  <td>{v.name}</td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    );
  }

The toggling of the state seems to be correct but the reflection is only happening for the first time.

https://codesandbox.io/s/zqno7m7j4p

Lodash's _.sortBy() doesn't have the ability to select descending or ascending. Use _.orderBy() instead ( sandbox ):

sort(key) {
  const columnState = !this.state[`toggle-${key}`];

  this.setState({
    [`toggle-${key}`]: columnState,
    data: orderBy(
      this.state.data,
      [key],
      columnState ? 'desc' : 'asc'
    )
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM