# umiHooks
# 安装
npm i @umijs/hooks --save
1
# 使用
import { useAsync } from '@umijs/hooks';
1
# useAPI
# useAPI默认用法
import { Spin } from 'antd';
import React from 'react';
import { useAPI } from '@umijs/hooks';
export default () => {
const { data, loading } = useAPI({
url: 'https://helloacm.com/api/random/?n=8&x=4',
});
return (
<Spin spinning={loading}>
<div>ID: {data}</div>
</Spin>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# useAPI手动触发执行
import { Button, Spin } from 'antd';
import React from 'react';
import { useAPI } from '@umijs/hooks';
export default () => {
const { data, loading, run } = useAPI({
url: 'https://helloacm.com/api/random/?n=8&x=4',
manual: true,
});
return (
<>
<Spin spinning={loading}>ID: {data}</Spin>
<Button
onClick={run}
style={{
marginTop: 16,
}}
>
fetch
</Button>
</>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# useAPI轮询
import { Button, Spin } from 'antd';
import React from 'react';
import { useAPI } from '@umijs/hooks';
export default () => {
const { data, loading, timer } = useAPI({
url: 'https://helloacm.com/api/random/?n=8&x=4',
pollingInterval: 3000,
});
return (
<>
<Spin spinning={loading}>ID: {data}</Spin>
<Button.Group
style={{
marginTop: 16,
}}
>
<Button onClick={timer.pause}>pause</Button>
<Button onClick={timer.stop}>stop</Button>
<Button onClick={timer.resume}>resume</Button>
</Button.Group>
</>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 修改request方法
import React from 'react';
import { Button, notification } from 'antd';
import { useAPI } from '@umijs/hooks';
export default () => {
const { run } = useAPI({
url: 'https://helloacm.com/api/random/?n=8&x=4',
manual: true,
method: (...args) => {
notification.success({
description: `request sent, url is ${args[0]}`,
message: 'fake request',
});
return new Promise(resolve => resolve(null));
},
});
return (
<>
<Button.Group>
<Button
onClick={run}
style={{
marginTop: 16,
}}
>
fetch
</Button>
</Button.Group>
</>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# useAsync
# useAntdTable
我们一般会使用 Antd 的 Table 组件来搭建,但是其中还是有很多逻辑,我们是无法避免的。
page,pageSize管理
pageSize 变化时重新进行异步请求
筛选条件变化时,重置 page,并重新请求数据
异步请求的 loading 处理
异步请求的竞态处理组件卸载时丢弃进行中的异步请求(很多人通常不处理,在某些情况会报警告)
const { tableProps } = useAntdTable(asyncFn);
const columns = [];
return (
<Table columns={columns} rowKey="id" {...tableProps} />
)
1
2
3
4
5
2
3
4
5
# useSearch
常见的异步搜索场景,我们一般要处理:
防抖
异步请求的 loading 处理
异步请求的请求时序控制
组件卸载时取消防抖及异步请求等逻辑
const { data, loading, onChange } = useSearch(asyncFn);
<Select
onSearch={onChange}
loading={loading}
>
{data.map((item)=><Option />)}
</Select>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8