先介绍一下什么是hook
Hook是React 16.8新增的个性,专门用在函数式组件,它能够代替class组件中react的其余个性,是理论工作中要罕用到的。
为什么举荐应用hook进行开发
hook是专门配合函数式组件开发应用的,能够用它代替class组件的一些生命周期,防止大量this引起的凌乱,因而hook便于开发,且更易于让开发者了解代码
以上是集体的简略总结,更多起因能够参考react官网:https://react.docschina.org/d…
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,在组件函数外应用了useState
const [variable, setVariable] = useState(0);
//谬误2,在组件函数外应用了useEffect
useEffect(() => {})
export default function useState_Demo() {
//在组件函数里应用才是正确的
const [variable, setVariable] = useState(0);
}
3、为了防止以上的谬误,能够 装置eslint-plugin-react-hooks
ESLint 插件来查看代码上谬误
自定义hook
hook就是一个函数,自定义hook是为了不便组件之间共享逻辑,其实就是对复用性能进行封装,自定义hook外部也调用了react自带的hook,命名要以use结尾
//自定义hook
function useHook(initState) {
const [variable, setVariable] = useState(initState)
return variable;
}
//应用自定义hook
export default function useState_Demo() {
const variableState = useHook(0)
}
可能你会纳闷,多个组件中应用雷同的 Hook 会共享 state 吗?
答案是:不会。因为每次调用react自带的hook都是单独互不影响的,所以自定义hook被多次重复调用也是单独互不影响的
发表回复