首页 > 解决方案 > 使用功能组件对反应进行排序

问题描述

我已经在 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() });
  };

标签: reactjsreact-functional-component

解决方案


除了设置状态的部分外,在功能组件中这样做几乎相同。您将拥有一个状态值和一个使用 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() });
  };

希望这能回答你的问题。


推荐阅读