zoukankan      html  css  js  c++  java
  • [React Typescript 2022] Type React hooks

    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 { ... }
  • 相关阅读:
    4408: [Fjoi 2016]神秘数
    UOJ #35. 后缀排序[后缀数组详细整理]
    POJ 2887 Big String
    搜索过滤grep(win下为findstr)
    解决putty自动断开的问题
    > >> 将错误输出到文件
    环境变量
    端口被占用,查看并杀死占用端口的进程
    查找文件路径find
    【vim使用】
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15745272.html
Copyright © 2011-2022 走看看