ahooks 常用hook

本文介绍了AHooks库中的多种实用Hook,包括请求管理(useRequest)、动态表单处理(useDynamicList)、虚拟滚动(useVirtualList)、防抖和节流函数、定时器、生命周期管理、状态管理、路由状态跟踪、存储管理、DOM操作、性能优化、事件订阅和异步锁定等,展示了如何优雅地管理React组件的复杂行为。
摘要由CSDN通过智能技术生成

官方文档:ahooks

较常用的hook推荐

  1. useRequest 请求
import {useRequest } from 'ahooks';

const getSome = async () => {};
const { data, loading, run } = useRequest(getSome, {
    debounceInterval: 500,
    manual: true,
  refreshDeps: [], // manual为false,可以按被动式触发
});


<div>
    提交结果:{JSON.stringify(data)}
</div>
<Button loading={loading} onClick={run}>
   提交
</Button>
  1. useDynamicList 动态表单
import { useDynamicList } from 'ahooks';
const { list, remove, getKey, push } = useDynamicList(['David', 'Jack']);
const { getFieldDecorator, validateFields } = props.form;

<Form>
    {
      list.map((item, index) => {
        <Form.Item key={getKey(index)}>
          {getFieldDecorator(`names[${getKey(index)}]`, {
            initialValue: item,
            rules: [{ required: true }],
          })(<Input />)}

          {list.length > 1 && <Icon type="minus-circle-o" onClick={() => remove(index)} />}

          <Icon type="plus-circle-o" onClick={() => push('')} />
        </Form.Item>
      })
    }
</Form>

<Button onClick={() => {
  const res = props.form.getFieldsValue().names;
  console.log((res || []).filter(item => item))
}}>
  提交
</Button>
  1. useVirtualList 虚拟滚动
import { useVirtualList } from 'ahooks';

const { list, containerProps, wrapperProps } = useVirtualList(Array.from(Array(99999).keys()), {
 overscan: 30, // 视区上、下额外展示的 dom 节点数量
 itemHeight: 60, // 行高度,静态高度可以直接写入像素值,动态高度可传入函数
});

<div {...containerProps}>
 <div {...wrapperProps}>
   { list.map(item => <div key={item.index}>{item.data}</div>) }
 </div>
</div>
  1. useDebounceFn 防抖
import { useDebounceFn } from 'ahooks';

const { run } = useDebounceFn(
  () => console.log('test'),
  { wait: 500 },
);

<div>
  <Button onClick={run}>
    Click fast!
  </Button>
</div>
  1. useThrottleFn 节流
import { useThrottleFn } from 'ahooks';

const { run } = useThrottleFn(
  () => console.log('test'),
  { wait: 500 },
);

<div>
  <Button onClick={run}>
    Click fast!
  </Button>
</div>
  1. useInterval 定时器
import { useInterval } from 'ahooks';

const [count, setCount] = useState(0);

useInterval(() => {
  setCount(count + 1);
}, 1000);

<div>count: {count}</div>;
  1. 生命钩子 useDebounceEffect、useThrottleEffect、useMount、useUpdateEffect、useUnmount、useUpdateLayoutEffect
  1. useUrlState
import useUrlState from '@ahooksjs/use-url-state';

const [state, setState] = useUrlState(
  { page: '1', pageSize: '10' },
);

<button
  onClick={() => {
    setState((s) => ({ page: Number(s.page) + 1 }));
  }}
>
  翻页
</button>
  1. useCookieState
import { useCookieState } from 'ahooks';

const [message, setMessage] = useCookieState('cookie-key');

<input
  value={message}
  onChange={(e) => setMessage(e.target.value)}
/>  
  1. useLocalStorageState
import { useLocalStorageState } from 'ahooks';

const [message, setMessage] = useLocalStorageState('store-key', 'default value');

<input
  value={message || ''}
  onChange={(e) => setMessage(e.target.value)}
/>
  1. useSessionStorageState
import { useLocalStorageState } from 'ahooks';

const [message, setMessage] = useLocalStorageState('store-key', 'default value');

<input
  value={message || ''}
  onChange={(e) => setMessage(e.target.value)}
  1. 在function comp上使用和class comp一样的setState语法
import { useSetState } from 'ahooks';

const [state, setState] = useSetState<State>({
  hello: '',
  count: 0,
});

<Button onClick={() => setState({ hello: 'world' })}>
  只改变state.hello,不影响state.count
</Button>
  1. useWhyDidYouUpdate 调试判断什么参数导致组件update
import { useWhyDidYouUpdate } from 'ahooks';

const [randomNum, setRandomNum] = useState(Math.random());

// 当组件更新时,会在console打印出来哪个发生变动,导致组件update
useWhyDidYouUpdate('useWhyDidYouUpdateComponent', { ...props, randomNum });
  1. 判断是否点击到元素外面
import { useClickAway } from 'ahooks';

const ref = useRef<HTMLDivElement>();
useClickAway(() => {
  console.log('点击到div外部了')
}, ref);

<div ref={ref}> test </div>
  1. 判断页面是否在可见状态
import { useDocumentVisibility } from 'ahooks';

const documentVisibility = useDocumentVisibility();
useEffect(() => {
  if (documentVisibility === 'visible') {
    console.log('当前页面在可见状态');
  } else {
    console.log('当前页面不在可见状态');
  }
}, [documentVisibility]);
  1. 优雅的使用useEventListener
import { useEventListener } from 'ahooks';

const ref = useRef<HTMLDivElement>();
useEventListener('click', () => console.log('点击了'), { target: ref });

<div ref={ref}>test</div>
  1. 让dom元素全屏展示
import { useFullscreen } from 'ahooks';

const ref = useRef();
const [isFullscreen, { setFull, exitFull, toggleFull }] = useFullscreen(ref);
<div ref={ref}>
  {isFullscreen ? '全屏中' : '不在全屏中'}
</div>
  1. 判断dom是否在可视区
import { useInViewport } from 'ahooks';

const ref = useRef();
const inViewPort = useInViewport(ref);

<div ref={ref}>
  {inViewPort ? 'div在可视区' : 'div不在可视区'}
</div>
  1. js响应式窗口宽度判断
import { configResponsive, useResponsive } from 'ahooks';

configResponsive({
  small: 0,
  middle: 800,
  large: 1200,
});

const responsive = useResponsive();
// responsive ---> {small: true, middle: true, large: false}
  1. 判断dom宽高变化
import { useSize } from 'ahooks';

const ref = useRef();
const size = useSize(ref);

<div ref={ref}>
 try to resize the preview window <br />
 dimensions -- width: {size.width} px, height: {size.height} px
  1. 获取选中的文案
import { useTextSelection } from 'ahooks';

const ref = useRef();
const selection = useTextSelection(ref);

<div ref={ref}>
  <p>Please swipe your mouse to select any text on this paragraph.</p>
</div>
  1. 代替useMemo、useRef的钩子

因为useMemo不能保证一定不会被重新计算

useRef如果针对复杂对象,每次渲染都创建一次会很耗性能

import { useCreation } from 'ahooks';

const foo = useCreation(() => {number: Math.random()}, []);
  1. 事件订阅
import { useEventEmitter } from 'ahooks';

// 事件队列
const focus$ = useEventEmitter<number>();

// 发送
focus$.emit(123);

// 订阅
focus$.useSubscription(value => {
  console.log(value);
});
  1. 锁定异步函数

在异步函数执行完前,再次触发会被忽略

import { useLockFn } from 'ahooks';

const submit = useLockFn(async () => {
  await requestSome();
});

<button onClick={submit}>Submit</button>

  1. 响应式修改state
import { useReactive } from 'ahooks';
const state = useReactive({
  count: 0,
  inputVal: '',
  obj: {
    value: '',
  },
});

<p> state.count:{state.count}</p>
<button onClick={() => state.count++}>
  state.count++
</button>
  • 39
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值