使用react Hooks通过数组映射-REFACTORING CODE

时间:2019-12-14 18:08:32

标签: reactjs react-hooks

我正在做一些练习,并构建了一些通过前端与之交互的API。现在,我将代码重构为使用钩子。但是,我得到的错误“ games.map”不是我的map方法的函数。

以下错误

TypeError: games.map is not a function
Games
src/components/pages/games/Games.js:29
  26 |     </div>
  27 |   </div>
  28 | </div>
> 29 | <div className="text-white text-dark">
     | ^  30 |   {games.map(game => {
  31 |     return <GameCard games={game} key={game.name} />;
  32 |   })}
View compiled
▶ 17 stack frames were collapsed.
(anonymous function)
src/components/pages/games/Games.js:14
  11 | 
  12 | const fetchAllGames = () => {
  13 |   api.getAllGames().then(games => {
> 14 |     gameState({ games });
     | ^  15 |   });
  16 | };
  17 | 
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

请参阅以下我要尝试映射的组件,对地图重构的任何帮助都将非常有用:)

import * as api from '../../../api';
import GameCard from '../gameCards/GameCards';

const Games = () => {
  const [games, gameState] = useState([]);

  useEffect(() => {
    fetchAllGames();
  });

  const fetchAllGames = () => {
    api.getAllGames().then(games => {
      gameState({ games });
    });
  };

  return (
    <div>
      <div className="container-fluid" style={{ height: 35 }}>
        <div className="row">
          <div className="col">
            <button to="" className="btn btn-primary">
              Add New Game
            </button>
          </div>
        </div>
      </div>
      <div className="text-white text-dark">
        {games.map(game => {
          return <GameCard games={game} key={game.name} />;
        })}
      </div>
    </div>
  );
};

export default Games;

2 个答案:

答案 0 :(得分:1)

.map仅适用于数组,不适用于对象

   api.getAllGames().then(games => {
      gameState({ games });
    });

在这里,您要设置带有对象的状态游戏。

我不知道游戏包含什么,但是如果它是一个数组,则应这样操作

gameState(games)

答案 1 :(得分:1)

解决方案:

由于useState的初始状态为Array 您应该使用String result = (String) router.get("OpenOrder").apply(order); 而不是gameState(games)

gameState{games}