繁体   English   中英

我如何从另一个不是反应组件的文件中调用 useReducer 调度 function? (不使用 Redux)

[英]How do i call a useReducer dispatch function from another file, which is not a react component? (without using Redux)

我有一个显示游戏板的 function 组件:“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?

简短的回答是:“你不能”。 Hooks can only be called inside of a React function component, and the dispatch function returned by the useReducer hook is only accessible inside the scope of that function component.

可以假设将dispatch function 传递给另一个模块,以便在需要时调用,但这会有点复杂。

我在这里的主要观察是,示例代码显示了一种非常 OOP 风格的方法来解决这个问题,这与使用 reducer 的方式完全相反。 我建议尝试重新考虑“控制器”逻辑,并在减速器本身内部进行管理。 这就是 reducer 的真正威力——你宣布“这个事件发生了”,然后让 reducer 负责弄清楚实际的 state 更新需要是什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM