reactjs - 使用功能组件对反应进行排序
问题描述
我已经在 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() });
};
解决方案
除了设置状态的部分外,在功能组件中这样做几乎相同。您将拥有一个状态值和一个使用 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() });
};
希望这能回答你的问题。
推荐阅读
- wcf - 与 BizTalk 2013r2 一起使用的 IIS 托管 WCF 服务上的客户端证书位置
- python - 如果 OpenCV 是用 pip 安装的,有没有办法从“samples”文件夹中读取图像?
- r - 确定向量的内容主要是正数还是负数
- javascript - 在 useEffect 挂钩中定义的函数内的状态变量在值更改时不会更新
- windbg - WinDbg 无法加载扩展
- r - 如何在 R 中计算卫星数据的区域(国家)平均值?
- r - 将行应用于名义行之间的值
- dart - 从 Dartz 中的不同 Either 返回一个 Either 对象
- sql - SQL Server:仅锁定一行并在并发访问中更新它
- c - 使用 sizeof 检查 int、char、float、double 的 10 元素数组中使用的内存,并找到数组中单个元素所需的内存