react-use 库

react-use 库文档(很好的文档)

# 定时器

  • # 封装

//useInterval.js
import { useEffect, useRef } from 'react'

const useInterval = (callback, delay) => {
  const savedCallback = useRef(() => {})

  useEffect(() => {
    savedCallback.current = callback
  })

  useEffect(() => {
    if (delay !== null) {
      const interval = setInterval(() => savedCallback.current(), delay || 0)
      return () => clearInterval(interval)
    }
    return undefined
  }, [delay])
}

export default useInterval
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • # 使用

import useInterval from './useInterval'

...
useInterval(()=>{
  ...
},1000)
...
1
2
3
4
5
6
7

# 布尔值

import { useCallback, useState } from 'react'

const useToggle = (initialValue) => {
  const [value, setValue] = useState(initialValue)

  const toggle = useCallback(
    (nextValue) => {
      if (typeof nextValue === 'boolean') {
        setValue(nextValue)
      } else {
        setValue((currentValue) => !currentValue)
      }
    },
    [setValue]
  )

  return [value, toggle]
}

export default useToggle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • # 使用

...
const [flag,toggle] =useToggle(false)
...
flag // false
toggle(false) //传参指定boolean值
toggle() //不传参取反
1
2
3
4
5
6

# 获取 state 改变前的值

import { useEffect, useRef } from 'react'

const usePrevious = (state) => {
  const ref = useRef()

  useEffect(() => {
    ref.current = state
  })

  return ref.current
}

export default usePrevious
1
2
3
4
5
6
7
8
9
10
11
12
13
Last Updated: 8/12/2020, 2:29:00 PM