在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Type useMemo: let rowArray = React.useMemo<null[]>( () => Array(board.rows).fill(null), [board.rows] );
Type useCallback: let getColumnArray = React.useCallback( (rowIndex: number): Cell[] => cells.slice( board.columns * rowIndex, board.columns * rowIndex + board.columns ), [board.columns, cells] );
Type useRef: let ref = React.useRef<HTMLButtonElement>(null); <Button ref={ref} ... />
Type useState: let [timeElapsed, setTimeElapsed] = React.useState<number>(0);
Type Custom hook: function useTimer(gameState): [number, () => void] { let [timeElapsed, setTimeElapsed] = React.useState<number>(0); React.useEffect(() => { if (gameState === "active") { let id = window.setInterval(() => { setTimeElapsed((t) => (t <= 999 ? ++t : t)); }, 1000); return () => { window.clearInterval(id); }; } }, [gameState]); const reset = React.useCallback(() => { setTimeElapsed(0); }, []); return [timeElapsed, reset]; }
Type useReducer: The best way to type a useReducer is typing `reducer` function itself. let [{ gameState, cells, mines }, send] = React.useReducer( reducer, initialContext, function getInitialContext(ctx) { return { ...ctx, cells: createCells(board), }; } ); interface BoardContext { gameState: GameState; cells: Cell[]; mines: number[]; initialized: boolean; } type BoardEvent = | { type: "RESET"; board: BoardConfig } | { type: "REVEAL_CELL"; board: BoardConfig; index: number } | { type: "REVEAL_ADJACENT_CELLS"; board: BoardConfig; index: number } | { type: "MARK_CELL"; index: number } | { type: "MARK_REMAINING_MINES"; board: BoardConfig }; function reducer(context: BoardContext, event: BoardEvent): BoardContext { ... }
|
请发表评论