Skip to content

Commit 22181d0

Browse files
committed
引入antd
1 parent dc6fc3b commit 22181d0

File tree

10 files changed

+178
-55
lines changed

10 files changed

+178
-55
lines changed

craco.config.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const CracoLessPlugin = require('craco-less');
2+
3+
module.exports = {
4+
plugins: [
5+
{
6+
plugin: CracoLessPlugin,
7+
options: {
8+
lessLoaderOptions: {
9+
lessOptions: {
10+
modifyVars: {'@primary-color': 'rgb(0,82,204)', '@font-size-base': '16px'},
11+
javascriptEnabled: true,
12+
},
13+
},
14+
},
15+
},
16+
],
17+
};

package.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
"version": "0.1.0",
44
"private": true,
55
"dependencies": {
6+
"@craco/craco": "^6.1.2",
67
"@testing-library/jest-dom": "^5.11.4",
78
"@testing-library/react": "^11.1.0",
89
"@testing-library/user-event": "^12.1.10",
910
"@types/jest": "^26.0.15",
1011
"@types/node": "^12.0.0",
1112
"@types/react": "^17.0.0",
1213
"@types/react-dom": "^17.0.0",
14+
"craco-less": "^1.17.1",
1315
"fetch": "^1.1.0",
1416
"jira-dev-tool": "^1.7.61",
1517
"qs": "^6.10.1",
@@ -20,9 +22,9 @@
2022
"web-vitals": "^1.0.1"
2123
},
2224
"scripts": {
23-
"start": "react-scripts start",
24-
"build": "react-scripts build",
25-
"test": "react-scripts test",
25+
"start": "craco start",
26+
"build": "craco build",
27+
"test": "craco test",
2628
"eject": "react-scripts eject",
2729
"json-server": "json-server __json_server_mock__/db.json --watch --port 3001 --middlewares ./__json_server_mock__/middleware.js"
2830
},

src/App.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import React from 'react';
22
import './App.css';
3-
import {LoginScreen} from "./screens/login";
43
import {useAuth} from "./context/auth-context";
54
import {AuthenticatedApp} from "./authenticated-app";
65
import {UnauthenticatedApp} from "./unauthenticated-app";

src/auth-provider.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const apiUrl = process.env.REACT_APP_API_URL
55
const localStorageKey = '__auth__provider__token'
66

77
export const getToken = () =>{
8-
window.localStorage.getItem(localStorageKey)
8+
return window.localStorage.getItem(localStorageKey)
99
}
1010

1111
export const handleUserResponse = ({user}: {user: User}) =>{

src/context/auth-context.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import React, {ReactNode, useState} from 'react'
22
import * as auth from 'auth-provider'
33
import {User} from "../screens/project-list/search-panel";
4+
import {http} from "../utils/http";
5+
import {useMount} from "../utils";
46

57

68
const AuthContext = React.createContext<{
@@ -17,6 +19,17 @@ interface AuthForm {
1719
password: string;
1820
}
1921

22+
//初始化user
23+
const bootstrapUser = async () =>{
24+
let user = null
25+
const token =auth.getToken()
26+
if(token){
27+
const data = await http('me', {token})
28+
user = data.user
29+
}
30+
return user
31+
}
32+
2033
export const AuthProvider = ({children}:{children: ReactNode}) =>{
2134
const [user, setUser] = useState<User | null>(null)
2235

@@ -25,6 +38,11 @@ export const AuthProvider = ({children}:{children: ReactNode}) =>{
2538
const register = (form: AuthForm) => auth.register(form).then(user => setUser(user))
2639
const logout = () => auth.logout().then(() => setUser(null))
2740

41+
//初始加载的时候
42+
useMount(()=>{
43+
bootstrapUser().then(setUser)
44+
})
45+
2846
return <AuthContext.Provider children={children} value={{user,login,register, logout}}></AuthContext.Provider>
2947
}
3048

src/index.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import './index.css';
44
import App from './App';
55
import reportWebVitals from './reportWebVitals';
66
import {loadDevTools} from 'jira-dev-tool'
7+
import 'antd/dist/antd.less'
78
import {AppProviders} from "./context";
89

910
loadDevTools(() => {

src/screens/login/index.tsx

Lines changed: 0 additions & 35 deletions
This file was deleted.

src/screens/project-list/index.tsx

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {List} from './list'
33
import React, {useEffect, useState} from "react";
44
import {cleanObject, useDebounce, useMount} from "../../utils";
55
import * as qs from "qs";
6+
import {useHttp} from "../../utils/http";
67
const apiUrl = process.env.REACT_APP_API_URL
78

89
export const ProjectListScreen = () =>{
@@ -13,22 +14,15 @@ export const ProjectListScreen = () =>{
1314
})
1415
const [list, setList] = useState([])
1516
const debouncedParam = useDebounce(param, 2000)
16-
17+
const client = useHttp()
1718

1819
useEffect(()=>{
19-
fetch(`${apiUrl}/projects?${qs.stringify(cleanObject(debouncedParam))}`).then(async res =>{
20-
if(res.ok){
21-
setList(await res.json())
22-
}
23-
})
20+
client('projects', {data:cleanObject(debouncedParam)}).then(setList)
2421
}, [debouncedParam])
2522

23+
//初始化的时候调用
2624
useMount(() =>{
27-
fetch(`${apiUrl}/users`).then(async res =>{
28-
if(res.ok){
29-
setUsers(await res.json())
30-
}
31-
})
25+
client('users').then(setUsers)
3226
})
3327

3428
return <div>

src/utils/http.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import qs from "qs"
2+
import * as auth from 'auth-provider'
3+
import {useAuth} from "../context/auth-context";
4+
5+
const apiUrl = process.env.REACT_APP_API_URL
6+
7+
interface Config extends RequestInit {
8+
token?: string;
9+
data?: object;
10+
}
11+
12+
export const http = async (endpoint: string, {data, token, headers, ...customConfig}: Config = {}) => {
13+
const config = {
14+
method: 'GET', //默认值为GET 如果customConfig有method传进来就会覆盖掉这里的值
15+
headers: {
16+
Authorization: token ? `Bearer ${token}` : '',
17+
'Content-Type': data ? 'application/json' : ''
18+
},
19+
...customConfig
20+
}
21+
22+
if (config.method.toUpperCase() === 'GET') {
23+
endpoint += `?${qs.stringify(data)}`
24+
} else {
25+
config.body = JSON.stringify(data || {})
26+
}
27+
28+
return window.fetch(`${apiUrl}/${endpoint}`, config).then(async res => {
29+
//token过期的时候
30+
if (res.status === 401) {
31+
await auth.logout() //退出重新登录
32+
window.location.reload() //页面刷新
33+
return Promise.reject({message: '请重新登录'})
34+
}
35+
const data = await res.json()
36+
if (res.ok) {
37+
return data
38+
} else {
39+
return Promise.reject(data)
40+
}
41+
})
42+
}
43+
44+
//只有Hook里面可以使用其他的Hook
45+
export const useHttp = () => {
46+
const {user} = useAuth()
47+
//utility type的用法:用泛型给它传入一个其它类型,然后utility type对这个类型进行某种操作
48+
return (...[endpoint, config]: Parameters<typeof http>) => http(endpoint, {...config, token: user?.token})
49+
}

0 commit comments

Comments
 (0)