简体   繁体   中英

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

I have a function component which displays a game board: "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 };

In the "GameController.ts" file, i'd like to dispatch an action to this component when i receive a response from the server.

const GameController = (() => {
  const updateEnemyBoard = (grid: number[][]) => {
    EnemyBoard.setGrid(grid);
    // need to call enemyBoardDispatch({type: "update"}) from here
  };
  return {
    sendAttack,
    receiveAttack,
    updateEnemyBoard,
  };
})();

export { GameController };

It's similar to this question but I'm not using redux in my project. Is it possible to do this or should i be looking into using redux?

The short answer is: "you can't". 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.

You could hypothetically take the dispatch function and pass it over to that other module for it to call when needed, but that would get a bit complicated.

My main observation here is that the sample code shows a very OOP-style approach to solving this problem, and that's really the opposite of how reducers get used. I would suggest trying to rethink the "controller" logic, and manage that inside of the reducer itself. That's really the power of reducers - you announce "this event happened", and let the reducer take care of figuring out what the actual state update needs to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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