您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

什么是hook?聊聊React中常用的两个Hook

2024/3/1 1:42:55发布20次查看
本篇文章带大家了解一下hook,聊聊为什么推荐使用hook进行开发,并介绍一下react最常用的两个hook,希望对大家有所帮助!
先介绍一下什么是hookhook是react 16.8新增的特性,专门用在函数式组件,它可以代替class组件中react的其他特性,是实际工作中要常用到的。【相关推荐:redis视频教程】
为什么推荐使用hook进行开发hook是专门配合函数式组件开发使用的,可以用它代替class组件的一些生命周期,避免大量this引起的混乱,因此hook便于开发,且更易于让开发者理解代码
以上是个人的简单总结,更多原因可以参考react官网:
https://react.docschina.org/docs/hooks-intro.html#motivation
usestate代码中:
react.usestate(0)相当于class组件中的this.state添加一个属性值
variable相当于class组件中的this.state. variable的值
setvariable可以用来修改variable的值,可以相当于class组件中的this.setstate
import react,(usestate) from 'react'export default function usestate_demo() { const [variable, setvariable] = usestate(0);//通过解构赋值,我们拿到的variable、setvariable function changevariable(){ setvariable((variable) => variable +1) //setvariable的回调中传进来的参数是variable } render ( <div> <button onclick = {change}>点我会使variable+1</button> </div> )}
useeffect代码中:
以下代码中可以看出,useeffect的使用代替了在class组件中componentdidmoun、componentdidupdate、componentwillunmount的使用
import react,(usestate, useeffect) from 'react'export default function usestate_demo() { const [variable, setvariable] = usestate(0);//通过解构赋值,我们拿到的variable、setvariable useeffect(() => { //这个return是在该组件监测的数据变化时或者被卸载时调用的,被卸载时调用可以相当于componentwillunmount钩子 return () => { console.log('该组件被卸载了') } }, [variable])//第二个参数传了[variable],表示检测variable的更新变化,一旦variable变化就会再次执行useeffect的回调 //第二个参数传了[],表示谁都不检测只执行一次useeffect的回调,相当于componentdidmount钩子 //第二个参数不传参,只要该组件有state变化就会执行useeffect的回调,相当于componentdidupdate钩子 function changevariable(){ setvariable((variable) => variable +1) //setvariable的回调中传进来的参数是variable } render ( <div> <button onclick = {change}>点我会使variable+1</button> </div> )}
使用hook需要注意的1、只在组件函数的最外层使用hook,不要在循环,条件或嵌套函数中调用 hook
import react,(useeffect) from 'react'export default function usestate_demo() { //这里才是正确的 useeffect(() => {}) //错误1,使用了条件判断 if(true) { useeffect(() => {}) } //错误2,使用了循环 while(true) { useeffect(() => {}) } //错误3,使用了嵌套 useeffect(() => { useeffect(() => {}) })}
2、不能在组件的函数外使用hook
import react,(usestate, useeffect) from 'react'//错误1,在组件函数外使用了usestateconst [variable, setvariable] = usestate(0);//错误2,在组件函数外使用了useeffectuseeffect(() => {})export default function usestate_demo() { //在组件函数里使用才是正确的 const [variable, setvariable] = usestate(0);}
3、为了避免以上的错误,可以 安装eslint-plugin-react-hooks eslint 插件来检查代码上错误
自定义hookhook就是一个函数,自定义hook是为了方便组件之间共享逻辑,其实就是对复用功能进行封装,自定义hook内部也调用了react自带的hook,命名要以use开头
//自定义hookfunction usehook(initstate) { const [variable, setvariable] = usestate(initstate) return variable;}//使用自定义hookexport default function usestate_demo() { const variablestate = usehook(0)}
可能你会疑惑,多个组件中使用相同的 hook 会共享 state 吗?
答案是:不会。因为每次调用react自带的hook都是独自互不影响的,所以自定义hook被多次重复调用也是独自互不影响的
更多编程相关知识,请访问:编程入门!!
以上就是什么是hook?聊聊react中常用的两个hook的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product