使用功能组件对反应进行排序
Posted
技术标签:
【中文标题】使用功能组件对反应进行排序【英文标题】:sorting in react using a function component 【发布时间】:2021-11-25 10:40:05 【问题描述】:我已经在 React 类组件中这样做了,但是我需要在 React 函数组件中这样做,因为我想学习将类组件转换为函数组件。
onSortByPlatformAsc = () =>
var sortByPlatform = this.state.listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
this.setState( listGames: sortByPlatform );
;
onSortByPlatformDesc = () =>
var sortByPlatform = this.state.listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
this.setState( listGames: sortByPlatform.reverse() );
;
【问题讨论】:
【参考方案1】:在功能组件中这样做几乎相同,除了您设置状态的部分。您将拥有一个状态值和一个使用 useState 挂钩设置状态的函数,如下所示:
const [games, setGames] = useState(
listGames:[]
)
那么你需要做的就是调用 setGames 函数并使用你想要设置的值如下
onSortByPlatformAsc = () =>
var sortByPlatform = this.state.listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
setGames( listGames: sortByPlatform );
;
onSortByPlatformDesc = () =>
var sortByPlatform = this.state.listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
setGames( listGames: sortByPlatform.reverse() );
;
希望这能回答你的问题。
【讨论】:
我的 useState 如下 const [listGames, setListGames] = useState(JSONDATA) 所以我认为 setState 在这里不起作用【参考方案2】:坦率地说,这并没有太大的不同。 这种情况下的区别主要是:
this
不再相关。
函数需要像常规函数或常量等一样声明。
state
不再是一个对象,虽然它可以是你想要的,但也可以是单独的状态,由内置的 useState
钩子声明。
您发布的代码应如下所示:
import useState from 'react';
function MyComponent()
const [listGames, setListGames] = useState([]);
const onSortByPlatformAsc = () =>
var sortByPlatform = state.listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
setListGames(sortByPlatform);
;
const onSortByPlatformDesc = () =>
var sortByPlatform = state.listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
setListGames(sortByPlatform.reverse());
;
如果您还有其他问题,请随时提问。
【讨论】:
【参考方案3】:为了在功能组件中使用状态,您应该使用useState()
钩子。另外功能组件中没有this
关键字。
import useState from 'react';
const [listGames, setListGames] = useState([])
onSortByPlatformAsc = () =>
var sortByPlatform = listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
setListGames(sortByPlatform);
;
onSortByPlatformDesc = () =>
var sortByPlatform = listGames.sort((a, b) =>
a.platform.localeCompare(b.platform)
);
setListGames(sortByPlatform.reverse());
【讨论】:
【参考方案4】:Array.prototype.sort
和 Array.prototype.reverse
都进行就地排序和排序。换句话说,他们改变了他们操作的数组。如果你在 React 状态上调用它,它会改变状态,这是 React 中的主要反模式。
假设您已将类组件 this.state.listGames
转换并存储到函数组件 listGames
useState
React 挂钩中:
const [listGames, setListGames] = React.useState([]);
我建议对代码进行一些分解以创建排序和逆排序比较器函数:
const sortComparator = (a, b) => a.platform.localeCompare(b.platform);
const inverseSortComparator = (a, b) => sortComparator(b, a);
使用功能状态更新来访问之前的状态,创建一个副本,然后使用比较器对其进行排序。
const onSortByPlatformAsc = () =>
setListGames(listGames => listGames.slice().sort(sortComparator));
;
要进行倒排,再次使用功能状态更新,创建副本,然后使用倒排比较器函数交换排序顺序。
const onSortByPlatformDesc = () =>
setListGames(listGames => listGames.slice().sort(inverseSortComparator));
;
【讨论】:
以上是关于使用功能组件对反应进行排序的主要内容,如果未能解决你的问题,请参考以下文章
如何避免在反应功能组件中对“静态组件”进行不必要的重新渲染?