HTTP 请求

APIClient 用于发起 HTTP 请求,在客户端应用的 插件生命周期 内,可以使用 app.apiClient 发起客户端请求,在组件内可以使用 useAPIClient()useRequest()

一. APIClient

插件中使用 APIClient

1// 在插件的 load() 方法中注入
2export default class MyPlugin {
3  async load() {
4    try {
5      // 发送 GET 请求
6      const users = await this.app.apiClient.request({ url: '/users' })
7
8      // 发送 POST 请求(带 JSON 数据)
9      const newUser = await this.app.apiClient.request({
10        url: '/users',
11        method: 'post',
12        data: { name: 'John Doe' },
13      })
14    } catch (error) {
15      console.error('请求失败:', error)
16    }
17  }
18}

组件内使用 APIClient

1import { useAPIClient, useRequest } from '@tachybase/client'
2
3const SampleComponent = () => {
4  const apiClient = useAPIClient()
5  const { data, loading } = useRequest({ url: '/posts' })
6  const fetchData = async () => {
7    const response = await apiClient.request({
8      url: '/search',
9      params: { q: 'value' },
10    })
11    console.log('搜索结果:', response.data)
12  }
13
14  return <div>SampleComponent</div>
15}

二. useRequest()

异步数据管理,可以是发起的客户端请求数据,也可以是自定义的异步函数。详细用法参考 ahooks 的 useRequest() 文档

1function useRequest<P>(
2  service: AxiosRequestConfig<P> | ResourceActionOptions<P> | FunctionService,
3  options?: Options<any, any>
4)
1// 基础请求状态管理
2const { data, loading, error, refresh } = useRequest({
3  url: '/api/data',
4  method: 'get',
5})
6
7// 带自定义查询参数的请求
8const { params, run } = useRequest({
9  url: '/search',
10  defaultParams: { type: 'post' },
11})
12
13// 手动触发查询
14run({ q: 'value', page: 3 })