如何正确的写一个react页面

前言

react实在是太灵活,导致我学习的时候一直找不到一个最佳实践,但还是摸索出了一点自己的写法,记录一下。

流程

先在screens文件夹下创建一个路由页面kanban.tsx,随便写一点东西:

1
2
3
4
5
6
7
8
import React from "react";
import { useDocumentTitle } from "../../utils/index";

export const KanbanScreen = () => {
useDocumentTitle("看板列表");
return <h1>看板</h1>;
};

接着定义一下这个页面所需要的基础类型,在types文件夹下新建一个kanban.ts

1
2
3
4
5
export interface Kanban {
id: number;
name: string;
projectId: number;
}

接着定义这个页面所需要的接口,在api文件夹下新建一个kanban.ts:

1
2
3
4
5
6
7
8
9
10
11
12
import http, { ResponseData } from "./index";
import { AxiosPromise, AxiosResponse } from "axios";

export const getKanbanInfo = (params?: Partial<Kanban>): Promise<AxiosResponse<Kanban[]>> => {
return http.request({
url: `/kanbans`,
method: "get",
params,
});
};


接着写这个页面所需要获取数据的逻辑,即hook,在utils文件夹下新建一个kanban.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
import { getKanbanInfo } from './../api/kanban';
import { useQuery } from "react-query";
import { Kanban } from "types/Kanban";



export const useKanbans = (param?: Partial<Kanban>) => {
return useQuery<Kanban[], Error>(["kanbans", param], async () => {
const res = await getKanbanInfo(param || {});
return res.data;
});
};

这就是一个基本流程。