[英]ReactJS Render not firing after data sort
使用 ReactJS 並嘗試在單擊表標題時對數據進行排序我遇到了一個問題,即數據確實已排序但未重新呈現:
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
我知道代碼是腳本方法的混合,因為我仍在學習 ES6; 但是,我認為上面的代碼應該可以工作。
請讓我知道我哪里會誤入歧途。 謝謝。
React setState
是一個異步函數,它期望一個值而不是一個函數。 你可以這樣做:
let newData = this.state.data.sort((a,b) => a.company.localeCompare(b.company));
this.setState({ data: newData });
希望這對你有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.