抽离 useTags 为自定义hook

  1. import {useState} from 'react';
  2. const useTags = () => {
  3. const [tags, setTags] = useState<string[]>(['衣','食', '住', '行'])
  4. return {
  5. tags,
  6. setTags
  7. }
  8. }
  9. export {useTags}
  • 必须以use开头
  • return一个对象,暴露数据和处理数据的接口

    文字过长时显示省略号

    1. .oneLine {
    2. overflow: hidden;
    3. white-space: nowrap;
    4. text-overflow: ellipsis;
    5. }
    image.png

    路由中使用exact精确匹配

    1. <Router>
    2. <Switch>
    3. <Route exact path="/tags">
    4. <Tags />
    5. </Route>
    6. <Route exact path="/tags/:tag">
    7. <Tag />
    8. </Route>
    9. </Switch>
    10. </Router>
    1. <TagList>
    2. {tags.map(tag =>
    3. <li key={tag}>
    4. <Link to={'/tags/'+tag}>
    5. <span className="oneLine">{tag}</span>
    6. <Icon name="right" />
    7. </Link>
    8. </li>)}
    9. </TagList>
    Link的作用是修改当前路径

    实现createId的两种方式

    函数实现 ```typescript let id = 0 const createId = () => { id += 1; return id; }

export {createId}

  1. 在需要的地方调用函数
  2. ```jsx
  3. import {useState} from 'react';
  4. import {createId} from './lib/createId';
  5. const defaultTags = [
  6. {id: createId(), name: '衣'},
  7. {id: createId(), name: '食'},
  8. {id: createId(), name: '住'},
  9. {id: createId(), name: '行'}]
  10. const useTags = () => {
  11. const [tags, setTags] = useState<{id: number, name: string}[]>(defaultTags)
  12. return {
  13. tags,
  14. setTags
  15. }
  16. }
  17. export {useTags}

注意不能放在id的初始化不能放在useTags里,不然每次调用useTags都会初始化一次
类实现

  1. let id = 0
  2. class Id {
  3. value: number;
  4. constructor() {
  5. id += 1
  6. this.value = id
  7. }
  8. }
  9. export {Id}

调用

  1. import {Id} from './lib/createId';
  2. const defaultTags = [
  3. {id: (new Id).value, name: '衣'},
  4. {id: (new Id).value, name: '食'},
  5. {id: (new Id).value, name: '住'},
  6. {id: (new Id).value, name: '行'}]

useParams

使用 useParams 获取路由参数

  1. type Params = {
  2. id: string;
  3. }
  4. const Tag:React.FC = () => {
  5. const {id} = useParams<Params>()
  6. // ...
  7. }
  8. export {Tag}