• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

[React Typescript 2022] Type React hooks

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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 { ... }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
使用 typescript ,提升 vue 项目的开发体验(2)发布时间:2022-07-18
下一篇:
TypeScript-枚举兼容性发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap