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 { ... }
  • 相关阅读:
    软件杯学习:python爬虫爬取新浪新闻并保存为csv格式
    操作系统实验1:时间片轮转和存储管理动态分区分配及回收
    软件测试
    实验6-使用TensorFlow完成线性回归
    实验一
    pycharm中设置anaconda环境
    架构之美读书笔记一
    2.1学习总结:决策树分类器
    python自学日记一
    爱甩卖网站正式上线啦
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15745272.html
Copyright © 2011-2022 走看看