ahooks最好的reacthook库官⽅⽂档:
以下总结⼀些个⼈认为⾮常实⽤的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>
2) 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 = FieldsValue().names;
console.log((res || []).filter(item => item))
}}>
提交
</Button>
3) useVirtualList 虚拟滚动
import { useVirtualList } from 'ahooks';
const { list, containerProps, wrapperProps } = useVirtualList(Array.from(Array(99999).keys()), {
overscan: 30, // 视区上、下额外展⽰的 dom 节点数量
sessionstorage和localstorage
itemHeight: 60, // ⾏⾼度,静态⾼度可以直接写⼊像素值,动态⾼度可传⼊函数
});
<div {...containerProps}>
<div {...wrapperProps}>
{ list.map(item => <div key={item.index}>{item.data}</div>) }
</div>
</div>
4) useDebounceFn 防抖
import { useDebounceFn } from 'ahooks';
const { run } = useDebounceFn(
() => console.log('test'),
{ wait: 500 },
);
<div>
<Button onClick={run}>
Click fast!
</Button>
</div>
5)useThrottleFn 节流
import { useThrottleFn } from 'ahooks';
const { run } = useThrottleFn(
() => console.log('test'),
{ wait: 500 },
);
<div>
<Button onClick={run}>
Click fast!
</Button>
</div>
6)useInterval 定时器
import { useInterval } from 'ahooks';
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000);
<div>count: {count}</div>;
7) ⽣命钩⼦ useDebounceEffect、useThrottleEffect、useMount、useUpdateEffect、useUnmount、useUpdateLayoutEffect
8)useUrlState state 往 url query 带上
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>
9) useCookieState state 存放到 cookie,下次回来还能
import { useCookieState } from 'ahooks';
const [message, setMessage] = useCookieState('cookie-key');
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
/
>
10) useLocalStorageState state 存放到 localStorage
import { useLocalStorageState } from 'ahooks';
const [message, setMessage] = useLocalStorageState('store-key', 'default value'); <input
value={message || ''}
onChange={(e) => setMessage(e.target.value)}
/>
11) useSessionStorageState state 存放到 sessionStorage import { useSessionStorageState } from 'ahooks';
const [message, setMessage] = useSessionStorageState('store-key', 'default-value'); <input
value={message}
onChange={(e) => {
setMessage(e.target.value);
}}
/>
12)在function comp上使⽤和class comp⼀样的setState语法import { useSetState } from 'ahooks';
const [state, setState] = useSetState<State>({
hello: '',
count: 0,
});
<Button onClick={() => setState({ hello: 'world' })}>
只改变state.hello,不影响unt
</Button>
13) useWhyDidYouUpdate 调试判断什么参数导致组件update import { useWhyDidYouUpdate } from 'ahooks';
const [randomNum, setRandomNum] = useState(Math.random());
// 当组件更新时,会在console打印出来哪个发⽣变动,导致组件update useWhyDidYouUpdate('useWhyDidYouUpdateComponent', { ...props, randomNum }); 14)判断是否点击到元素外⾯
import { useClickAway } from 'ahooks';
const ref = useRef<HTMLDivElement>();
useClickAway(() => {
console.log('点击到div外部了')
}, ref);
<div ref={ref}> test </div>
15)判断页⾯是否在可见状态
import { useDocumentVisibility } from 'ahooks';
const documentVisibility = useDocumentVisibility();
useEffect(() => {
if (documentVisibility === 'visible') {
console.log('当前页⾯在可见状态');
} else {
console.log('当前页⾯不在可见状态');
}
}, [documentVisibility]);
16)优雅的使⽤useEventListener
import { useEventListener } from 'ahooks';
const ref = useRef<HTMLDivElement>();
useEventListener('click', () => console.log('点击了'), { target: ref });
<div ref={ref}>test</div>
17)让dom元素全屏展⽰
import { useFullscreen } from 'ahooks';
const ref = useRef();
const [isFullscreen, { setFull, exitFull, toggleFull }] = useFullscreen(ref); <div ref={ref}>
{isFullscreen ? '全屏中' : '不在全屏中'}
</div>
18)判断dom是否在可视区
import { useInViewport } from 'ahooks';
const ref = useRef();
const inViewPort = useInViewport(ref);
<div ref={ref}>
{inViewPort ? 'div在可视区' : 'div不在可视区'}
</div>
19)js响应式窗⼝宽度判断
import { configResponsive, useResponsive } from 'ahooks'; configResponsive({
small: 0,
middle: 800,
large: 1200,
});
const responsive = useResponsive();
// responsive ---> {small: true, middle: true, large: false}
20)判断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
</div>
21)获取选中的⽂案
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>
21)代替useMemo、useRef的钩⼦
因为useMemo不能保证⼀定不会被重新计算
useRef如果针对复杂对象,每次渲染都创建⼀次会很耗性能import { useCreation } from 'ahooks';
const foo = useCreation(() => {number: Math.random()}, []);
22)事件订阅
import { useEventEmitter } from 'ahooks';
// 事件队列
const focus$ = useEventEmitter<number>();
// 发送
focus$.emit(123);
// 订阅
focus$.useSubscription(value => {
console.log(value);
});
23)锁定异步函数
在异步函数执⾏完前,再次触发会被忽略
import { useLockFn } from 'ahooks';
const submit = useLockFn(async () => {
await requestSome();
});
<button onClick={submit}>Submit</button>
24)响应式修改state
import { useReactive } from 'ahooks';
const state = useReactive({
count: 0,
inputVal: '',
obj: {
value: '',
},
});
<p> unt:{unt}</p>
<button onClick={() => unt++}>
</button>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。