简体   繁体   中英

ReactJS Render not firing after data sort

Using ReactJS and attempting to sort data on the click of a table header I am running into a problem where the data DOES get sorted but not getting re-rendered:

import React, { Component } from 'react';

import "../styles/datagrid.min.css";
import "../styles/customers.min.css";

import {loadLocal} from "../globals"

class Customers extends Component {
  constructor(props){
    super(props)
    this.sortData = this.sortData.bind(this);
    this.formatRows = this.formatRows.bind(this);
    this.state = {data: []}
  }
  formatRows(){
    return(this.state.data.map(function(item,ndx){
      return(
        <tr key={ndx}>
          <td><input type="checkbox"/></td>
          <td>{item.company}<p>{item.address}</p></td>
          <td>{item.email}</td>
          <td>{item.telephone}</td>
          <td>{item.balance}</td>
          <td><button dataid={item.id}>Edit</button></td>
        </tr>
      )
    }));
  }
  sortData(e){
    switch (e.target.getAttribute("col")) {
    case "1":
      this.setState(prevState =>{
        this.state.data.sort((a,b)=>(a.company.localeCompare(b.company)))
      });
      break;
    default:
      break;
    }
  }
  componentDidMount(){
    let me = this;
    loadLocal("customers.json",function(data){me.setState({data:data});
  }
  render() {
    return(
      <div id="customers-layout">
          <header><h2>Customer Information</h2></header>
          <section style={{height:this.state.sectionHeight}}>
            <table className="datagrid">
              <thead>
                <tr>
                  <th><input type="checkbox"/></th>
                  <th col="1" onClick={this.sortData}>Customer Name</th>
                  <th col="2" onClick={this.sortData}>Email Address</th>
                  <th col="3" onClick={this.sortData}>Telephone Number</th>
                  <th col="4" onClick={this.sortData}>Balance</th>
                  <th col="5">Action</th>
                </tr>
              </thead>
              <tbody style={{height:this.state.tableHeight}}>{this.formatRows()}</tbody>
            </table>
          </section>
          <footer>Gonna Put The Calcs Here!</footer>
        </div>
    )
  }
};
export default Customers

I get that the code is a mixup of script methodologies as I am still learning ES6; however, I would think that the above code should work.

Please let me know where I am going astray. Thanks.

React setState is an asynchronous function which expect a value not a function. You can do it like this:

let newData = this.state.data.sort((a,b) => a.company.localeCompare(b.company));
this.setState({ data: newData });

Hope this works for you.

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