【发布时间】:2021-06-09 21:22:13
【问题描述】:
我有一个显示游戏板的功能组件:“EnemyBoardComponent.tsx”
const enemyBoardReducer = (state:number[][], action:Action)=>{
switch(action.type){
case "update":
{
return EnemyBoard.getGrid();
}
}
}
const EnemyBoardComponent: React.FC<Props> = (props) => {
const [enemyBoard, enemyBoardDispatch] = useReducer(enemyBoardReducer,EnemyBoard.getGrid());
const handleClick = (posX: number, posY: number) => {
GameController.sendAttack(posX, posY);
};
return (
<div className="gameboard">
//code to map the gameboard
</div>
);
};
export { EnemyBoardComponent };
在“GameController.ts”文件中,当我收到来自服务器的响应时,我想向该组件发送一个动作。
const GameController = (() => {
const updateEnemyBoard = (grid: number[][]) => {
EnemyBoard.setGrid(grid);
// need to call enemyBoardDispatch({type: "update"}) from here
};
return {
sendAttack,
receiveAttack,
updateEnemyBoard,
};
})();
export { GameController };
这类似于这个问题,但我没有在我的项目中使用 redux。有可能这样做还是我应该考虑使用 redux?
【问题讨论】:
-
UseReducer 钩子
-
我已经在使用 useReducer 钩子了。我的问题是如何从另一个文件调度一个动作。
-
看起来钩子可以而且只能从 React 函数组件中调用 reactjs.org/docs/hooks-rules.html
-
我明白了,这也适用于调度吗?我不想在组件之外调用钩子。只需要发送一个动作来更新状态。我需要使用问题中链接帖子中提到的 redux 吗?
标签: javascript reactjs typescript redux