抽离 useTags 为自定义hook
import {useState} from 'react';
const useTags = () => {
const [tags, setTags] = useState<string[]>(['衣','食', '住', '行'])
return {
tags,
setTags
}
}
export {useTags}
- 必须以use开头
- return一个对象,暴露数据和处理数据的接口
文字过长时显示省略号
.oneLine {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
路由中使用exact精确匹配
<Router>
<Switch>
<Route exact path="/tags">
<Tags />
</Route>
<Route exact path="/tags/:tag">
<Tag />
</Route>
</Switch>
</Router>
Link的作用是修改当前路径<TagList>
{tags.map(tag =>
<li key={tag}>
<Link to={'/tags/'+tag}>
<span className="oneLine">{tag}</span>
<Icon name="right" />
</Link>
</li>)}
</TagList>
实现createId的两种方式
函数实现 ```typescript let id = 0 const createId = () => { id += 1; return id; }
export {createId}
在需要的地方调用函数
```jsx
import {useState} from 'react';
import {createId} from './lib/createId';
const defaultTags = [
{id: createId(), name: '衣'},
{id: createId(), name: '食'},
{id: createId(), name: '住'},
{id: createId(), name: '行'}]
const useTags = () => {
const [tags, setTags] = useState<{id: number, name: string}[]>(defaultTags)
return {
tags,
setTags
}
}
export {useTags}
注意不能放在id的初始化不能放在useTags里,不然每次调用useTags都会初始化一次
类实现
let id = 0
class Id {
value: number;
constructor() {
id += 1
this.value = id
}
}
export {Id}
调用
import {Id} from './lib/createId';
const defaultTags = [
{id: (new Id).value, name: '衣'},
{id: (new Id).value, name: '食'},
{id: (new Id).value, name: '住'},
{id: (new Id).value, name: '行'}]
useParams
使用 useParams 获取路由参数
type Params = {
id: string;
}
const Tag:React.FC = () => {
const {id} = useParams<Params>()
// ...
}
export {Tag}