state 状态相关

useGetState

React.useState 增加了一个 getter 方法,以获取当前最新值。

js 复制代码
import { useState, useCallback } from 'react';

export type SetState<S> = S | ((prevState: S) => S);

function useGetState<S>(initialState: S | (() => S)) {
  const [state, setState] = useState(initialState);
  
  // 使用 ref 保存最新的 state 值
  const stateRef = useRef(state);
  stateRef.current = state;
  
  // 获取当前状态的方法
  const getState = useCallback(() => stateRef.current, []);
  
  // 包装 setState,同时更新 ref
  const setSetState = useCallback((setStateAction: SetState<S>) => {
    setState(prevState => {
      const nextState = setStateAction instanceof Function 
        ? setStateAction(prevState) 
        : setStateAction;
      stateRef.current = nextState;
      return nextState;
    });
  }, []);

  return [state, setSetState, getState] as const;
}

useResetState

提供重置 state 方法的 Hooks,用法与 React.useState 基本一致。

js 复制代码
import { useState, useRef, useCallback } from 'react';

type Dispatch<T> = (value: T | ((prevState: T) => T)) => void;

function useResetState<S>(initialState: S | (() => S)): [S, Dispatch<S>, () => void] {
  const [state, setState] = useState(initialState);
  const initialRef = useRef(initialState);
  
  const reset = useCallback(() => {
    setState(initialRef.current);
  }, []);
  
  return [state, setState, reset];
}
相关推荐
陈天伟教授1 小时前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
信看2 小时前
NMEA-GNSS-RTK 定位html小工具
前端·javascript·html
Tony Bai2 小时前
【API 设计之道】04 字段掩码模式:让前端决定后端返回什么
前端
苏打水com3 小时前
第十四篇:Day40-42 前端架构设计入门——从“功能实现”到“架构思维”(对标职场“大型项目架构”需求)
前端·架构
king王一帅3 小时前
流式渲染 Incremark、ant-design-x markdown、streammarkdown-vue 全流程方案对比
前端·javascript·人工智能
苏打水com3 小时前
第十八篇:Day52-54 前端跨端开发进阶——从“多端适配”到“跨端统一”(对标职场“全栈化”需求)
前端
Bigger3 小时前
后端拒写接口?前端硬核自救:纯前端实现静态资源下载全链路解析
前端·浏览器·vite
BD_Marathon3 小时前
【JavaWeb】路径问题_前端绝对路径问题
前端
whyfail4 小时前
Vue原理(暴力版)
前端·vue.js