Skip to content

Commit

Permalink
引入antd
Browse files Browse the repository at this point in the history
  • Loading branch information
kbin24 committed May 5, 2021
1 parent dc6fc3b commit 22181d0
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 55 deletions.
17 changes: 17 additions & 0 deletions craco.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const CracoLessPlugin = require('craco-less');

module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: {'@primary-color': 'rgb(0,82,204)', '@font-size-base': '16px'},
javascriptEnabled: true,
},
},
},
},
],
};
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@craco/craco": "^6.1.2",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"craco-less": "^1.17.1",
"fetch": "^1.1.0",
"jira-dev-tool": "^1.7.61",
"qs": "^6.10.1",
Expand All @@ -20,9 +22,9 @@
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject",
"json-server": "json-server __json_server_mock__/db.json --watch --port 3001 --middlewares ./__json_server_mock__/middleware.js"
},
Expand Down
1 change: 0 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react';
import './App.css';
import {LoginScreen} from "./screens/login";
import {useAuth} from "./context/auth-context";
import {AuthenticatedApp} from "./authenticated-app";
import {UnauthenticatedApp} from "./unauthenticated-app";
Expand Down
2 changes: 1 addition & 1 deletion src/auth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const apiUrl = process.env.REACT_APP_API_URL
const localStorageKey = '__auth__provider__token'

export const getToken = () =>{
window.localStorage.getItem(localStorageKey)
return window.localStorage.getItem(localStorageKey)
}

export const handleUserResponse = ({user}: {user: User}) =>{
Expand Down
18 changes: 18 additions & 0 deletions src/context/auth-context.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React, {ReactNode, useState} from 'react'
import * as auth from 'auth-provider'
import {User} from "../screens/project-list/search-panel";
import {http} from "../utils/http";
import {useMount} from "../utils";


const AuthContext = React.createContext<{
Expand All @@ -17,6 +19,17 @@ interface AuthForm {
password: string;
}

//初始化user
const bootstrapUser = async () =>{
let user = null
const token =auth.getToken()
if(token){
const data = await http('me', {token})
user = data.user
}
return user
}

export const AuthProvider = ({children}:{children: ReactNode}) =>{
const [user, setUser] = useState<User | null>(null)

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

//初始加载的时候
useMount(()=>{
bootstrapUser().then(setUser)
})

return <AuthContext.Provider children={children} value={{user,login,register, logout}}></AuthContext.Provider>
}

Expand Down
1 change: 1 addition & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {loadDevTools} from 'jira-dev-tool'
import 'antd/dist/antd.less'
import {AppProviders} from "./context";

loadDevTools(() => {
Expand Down
35 changes: 0 additions & 35 deletions src/screens/login/index.tsx

This file was deleted.

16 changes: 5 additions & 11 deletions src/screens/project-list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {List} from './list'
import React, {useEffect, useState} from "react";
import {cleanObject, useDebounce, useMount} from "../../utils";
import * as qs from "qs";
import {useHttp} from "../../utils/http";
const apiUrl = process.env.REACT_APP_API_URL

export const ProjectListScreen = () =>{
Expand All @@ -13,22 +14,15 @@ export const ProjectListScreen = () =>{
})
const [list, setList] = useState([])
const debouncedParam = useDebounce(param, 2000)

const client = useHttp()

useEffect(()=>{
fetch(`${apiUrl}/projects?${qs.stringify(cleanObject(debouncedParam))}`).then(async res =>{
if(res.ok){
setList(await res.json())
}
})
client('projects', {data:cleanObject(debouncedParam)}).then(setList)
}, [debouncedParam])

//初始化的时候调用
useMount(() =>{
fetch(`${apiUrl}/users`).then(async res =>{
if(res.ok){
setUsers(await res.json())
}
})
client('users').then(setUsers)
})

return <div>
Expand Down
49 changes: 49 additions & 0 deletions src/utils/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import qs from "qs"
import * as auth from 'auth-provider'
import {useAuth} from "../context/auth-context";

const apiUrl = process.env.REACT_APP_API_URL

interface Config extends RequestInit {
token?: string;
data?: object;
}

export const http = async (endpoint: string, {data, token, headers, ...customConfig}: Config = {}) => {
const config = {
method: 'GET', //默认值为GET 如果customConfig有method传进来就会覆盖掉这里的值
headers: {
Authorization: token ? `Bearer ${token}` : '',
'Content-Type': data ? 'application/json' : ''
},
...customConfig
}

if (config.method.toUpperCase() === 'GET') {
endpoint += `?${qs.stringify(data)}`
} else {
config.body = JSON.stringify(data || {})
}

return window.fetch(`${apiUrl}/${endpoint}`, config).then(async res => {
//token过期的时候
if (res.status === 401) {
await auth.logout() //退出重新登录
window.location.reload() //页面刷新
return Promise.reject({message: '请重新登录'})
}
const data = await res.json()
if (res.ok) {
return data
} else {
return Promise.reject(data)
}
})
}

//只有Hook里面可以使用其他的Hook
export const useHttp = () => {
const {user} = useAuth()
//utility type的用法:用泛型给它传入一个其它类型,然后utility type对这个类型进行某种操作
return (...[endpoint, config]: Parameters<typeof http>) => http(endpoint, {...config, token: user?.token})
}
Loading

0 comments on commit 22181d0

Please sign in to comment.