React中自定义hooks

279 阅读2分钟

前言:

何时使用或者说正确使用自定义hooks呢?让我们带着疑问往下看......

分析

首先可以从应用场景分析,比如能够逻辑复用,看下面这两段代码

  1. 发送验证码倒计时

export default function Djs () {

const [count, newcoubt] = useState(5)

const [isshow, newisshow] = useState(false)

const time = useRef(null)

const down = () => {

time.current = setInterval(() => {

newisshow(true)

newcoubt((state) => {

if (state === 0) {

clearInterval(time.current)

newisshow(false)

newcoubt(5)

} else {

return state - 1

}

})

}, 1000)

}

console.log(time.current)

return (

<div>

<button onClick={down} disabled={isshow}>

{isshow ? count + '秒后再试' : '发送验证码'}

</button>

</div>

)

}

  1. 页面不存在跳到首页

export default function Djs () {

const [count, newcoubt] = useState(5)

const time = useRef(null)

const down = () => {

time.current = setInterval(() => {

newcoubt((state) => {

if (state === 0) {

clearInterval(time.current)

newcoubt(5)

location.href = 'https://www.baidu.com'

} else {

return state - 1

}

})

}, 1000)

}

useEffect(() => {

down()

}, [])

console.log(time.current)

return (

<div>

<div>页面不存在{count}后跳转首页</div>

</div>

)

}

看这两段代码的发现很大部分都相同,只是它们处理的事情不同,所以我们可以把相同的部分抽离出来,封装自定义的hooks

首先我们要知道自定义hooks是一个函数,函数名必须以use开头,React就是通过函数名称是否以use开头来判断是不是hooks

hooks只能在函数式组件自定义hooks中使用,否则会报错

自定义hooks用来提取组件的状态逻辑,根据不同的功能有不同的返回值

我们把逻辑相同的代码抽离出来,然后进行改造。

创建一个jsx 命名如:zdy.jsx


import { useEffect, useRef, useState } from 'react'

export default function useCount (state, callBack = () => {}) {

// state:倒计时的时间,callBack倒计时完后要做的处理的事情 函数

const time = useRef(null)

const [count, newcoubt] = useState(state)

const start = () => {

newcoubt(state)

time.current = setInterval(() => {

newcoubt((state) => {

return state - 1

})

}, 1000)

}

  


useEffect(

() => {

if (count === 0) {

callBack()

clearInterval(time.current)

}

},

[count]

)

return { count, start } // 返回倒计时计数和开始倒计时的函数

}

  


改造完成后在发送验证码使用(页面不存在跳到首页类似)


import React, { useState } from 'react'

import ReactDOM from 'react-dom/client'

import useCount from './zdy'

  


export default function Djs () {

const [isshow, newisshow] = useState(false)

// useCount(倒计时时间,处理的函数)返回倒计时计数和开始倒计时的函数

const { count, start } = useCount(4, () => {

newisshow(false)

})

const down = () => {

newisshow(true)

start()

}

return (

<div>

<button onClick={down} disabled={isshow}>

{isshow ? count + '秒后再试' : '发送验证码'}

</button>

</div>

)

}

  


ReactDOM.createRoot(document.getElementById('root')).render(<Djs />)

  


总结

自定义hooks是一个函数,必须以use开头,只能在函数式组件和自定义hooks中使用。

自定义hooks可以让代码写的更优质。

感谢阅读🙆‍♂