React ts axios && react-query
首先我们需要安装这两个库
1.安装axios【可以参考这里】
$ npm install axios
# or
$ bower install axios
# or
$ yarn add axios
2.安装 react-query 【可以参考这里】
$ npm i react-query
# or
$ yarn add react-query
对axios进行二次封装
./src/request/https.ts
import axios from 'axios'
const httpBaseUrl = 'https://v1.hitokoto.cn'
const http = axios.create({
baseURL: httpBaseUrl,
timeout: 10000,
})
export { http }
./src/request/one_page.request.ts
import { http } from "./https";
export const getText = () => http.get("/");
./src/request/index.ts
export * from './one_page.request'
配置 react-query
/main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
+import { QueryClientProvider, QueryClient } from "react-query";
import App from "./App.tsx";
import "./index.css";
+const queryClient = new QueryClient()
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
+ <QueryClientProvider client={queryClient}>
<App />
+ </QueryClientProvider>
</React.StrictMode>
);
使用 react-query
./src/components/loading.tsx
import { FC } from "react";
import { Spin } from "antd";
const Index: FC = () => {
return (
<>
<Spin />
</>
);
};
export default Index;
./src/pages/one/index.tsx
import { FC } from "react";
import { getText } from "../../request";
import { useQuery } from "react-query";
import Loading from "../../components/loading";
const Index: FC = () => {
const { data, isLoading } = useQuery("text", getText);
if (!isLoading) {
const { id, hitokoto, from, from_who } = data!.data;
return (
<ul>
<li>{id}</li>
<li>{hitokoto}</li>
<li>{from}</li>
<li>{from_who}</li>
</ul>
);
} else {
return <Loading />;
}
};
export default Index;
【react-query 中 对 promise 进行了很多的处理,因此我们不用再 then 了】
【详细内容可以参考 API REFERENCE】