Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。
一 项目结构文件
- const.ts
/** select下拉框 */
export const option = [
{ label: '选项1', key: '1' },
{ label: '选项2', key: '2' },
{ label: '选项3', key: '3' },
]
- service.ts
import request from '@/utils/request';
/** get接口 */
export async function postService(params: any) {
return request('/aa/bb', {
method: 'POST',
data: params
})
}
/** post接口 */
export async function getService (params: any) {
return request('/aa/bb', {
method: 'GET',
params
})
}
- interface.ts文件,一般用于存放ts类型
export interface ItemType {
name: string
age: number | number // | 标示或
fn1: () => void // 无参数,无返回值
fn2: (parame: number) => number // 数字格式参数且返回值为数字格式
fn3: (parame?: number) => void // ?参数可传可不传
fn4: (par1?: number, par2: number) => void // fn4(undefined, 6) 如果不想传第一个参数,可传undefined
}
export interface RouteParams {
taskId: number
}
二 React Hooks(钩子)
- useState
const [list, setList] = useState<ItemType[]>([]) // 创建
setList([...list]) // 修改
- useEffect
useEffect(() => {
console.log('空数组,触发一次')
}, [])
useEffect(() => {
console.log('监听list,useState钩子修改了list触发')
}, [list])
- useRef
import React, { useRef } from 'react'
const Aaa = () => {
const inputValue = useRef<String>('') // 创建
inputValue.current = '新值' // 修改
const inputDom = useRef<any>() // 创建
inputDom.current.focus() // 获取dom并使input聚焦
return (
<input ref={inputDom} type="text" />
)
}
export default Aaa
三 React Router(路由)
- useHistory
import { useHistory, useParams } from 'umi'
const { push, replace, location, goBack, goForward, action, listen } = useHistory()
跳转及获参,push添加replace替换,用法完全一样
第一种 // url里显示
1.定义
path: '/aa/bb/:id/:typeId'
2.携参跳转
push(`/aa/bb?id=${record.id}${record.typeId}`)
3.获取
const { id, typeId } = useParams<any>()
第二种 // 显示
1.定义
path: '/aa/bb'
2.携参跳转
push(`/aa/bb?id=${record.id}&typeId=${record.typeId}`)
或
path({pathname: '/home', query: {id: 1, typeId: 2}})
3.获取
const { id, typeId } = location.query
第三种 // 不显示
1. 定义
path: '/aa/bb'
2.携参跳转
path('/aa/bb', {id: 1, typeId: 2})
3.获取
const { id, typeId } = location.state
返回
goBack()
前进
goForward()
获取pathname
const { pathname } = location // /aa/bb
获取跳转类型
const routerType = action // PUSH || REPLACE || ....
监听
listen(callback) // 每次触发都会重复挂载,挂载后任何页面跳转,只要路由变化,都会触发callback函数
const callback = (parameter, routerType) => {
parameter = {
pathname: "/aiLogin",
query: {id: "1"},
search: "?id=1",
...
} // 此页面路由数据
router = 'PUSH' || 'REPLACE' // 跳转类型
}
- history
import { history } from 'umi'
用法和useHistory一样,区别是history是对象,useHistory是函数,需要先在顶部先定义然后调用()
useHistory
const a = useHistory()
a.push('...')
----
history
history.push('...')