【发布时间】:2020-11-10 13:12:02
【问题描述】:
我正在将 React 组件从类转换为函数。我能够更改大部分代码,但是我在某一时刻卡住了。特别是 this.state 有一个 index 的这个函数:
const sortRows = (rows,property,sortBy) => {
if (this.state[sortBy] === 'asc'){
rows.sort(function(a,b){
if (a[property] !== null && b[property] !== null){
return a[property].localeCompare(b[property]);}
})
}
if (this.state[sortBy] === 'desc'){
rows.sort(function(a,b){
if (a[property] !== null && b[property] !== null){
return b[property].localeCompare(a[property]);}
})
}
return rows
}
上面的函数是这样调用的:
rows = sortRows(rows, "field_firstname", "sortFirstName");
其中sortFirstName 是另一个状态变量。
如何将this.state[sortBy] 转换为函数方法?
【问题讨论】:
-
通过快速扫描,我认为您需要重构它,以便
sortBy成为排序列的数组,即let [sortBy, setSortBy] = useState([]);和const sortRows = (rows, property, sortByIndex) => { if (sortBy[sortByIndex] === 'asc'){ //... } }。您可以这样设置状态,setSortByIndex = (index, direction) => setSortBy([...sortBy, index: direction ])(其中direction是'asc'或'desc') -
我已经尝试了第一部分。它不会触发任何错误,但不会对列进行排序。我应该如何使用代码的第二部分(
setSortByIndex)? -
目前如何设置 sortBy 列索引?另外,什么时候调用
sortRows?
标签: reactjs function react-hooks react-state-management