我正在 ReactJS 中构建一个简单的应用程序,它通过调用某个 API 来使用 JSON 数组。然后我将数组的结果填充到表中。我现在想让表的列可排序。我理想的情况是同时进行升序和降序排序。一旦我单击标题,当它按升序排序时,它应该按降序排序,反之亦然。这是我的代码。
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = { data: [] };
}
componentDidMount() {
fetch("http://hostname:xxxx/yyyy/zzzz")
.then(function(response) {
return response.json();
})
.then(items => this.setState({ data: items }));
}
render() {
var newdata = this.state.data;
return (
<table className="m-table">
<thead>
<tr>
<th>AccountName</th>
<th>ContractValue</th>
</tr>
</thead>
<tbody>
{newdata.map(function(account, index) {
return (
<tr key={index} data-item={account}>
<td data-title="Account">{account.accountname}</td>
<td data-title="Value">{account.negotiatedcontractvalue}</td>
</tr>
);
})}
</tbody>
</table>
);
}
}
export default ParentComponent;
您可以添加一个sort
财产归您所在州column
and direction
特性:
state = {
data: [],
sort: {
column: null,
direction: 'desc',
},
};
当然,您还应该有一个排序处理程序,如下所示:
onSort = (column) => (e) => {
const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
const sortedData = this.state.data.sort((a, b) => {
if (column === 'accountName') {
const nameA = a.accountName.toUpperCase(); // ignore upper and lowercase
const nameB = b.accountName.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
} else {
return a.contractValue - b.contractValue;
}
});
if (direction === 'desc') {
sortedData.reverse();
}
this.setState({
data: sortedData,
sort: {
column,
direction,
}
});
};
我得到了排序MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.
这是一支样本笔:https://codepen.io/anon/pen/xrGJKv https://codepen.io/anon/pen/xrGJKv
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)