1.State Hooks
useState是react自带的一个hook函数,它的作用就是用来声明状态变量。useState这个函数接收的参数是我们的状态初始值(initial state),它返回了一个数组,这个数组的第[0]项是当前当前的状态值,第[1]项是可以改变状态值的方法函数。
所以我们做的事情其实就是,声明了一个状态变量count,把它的初始值设为0,同时提供了一个可以更改count的函数setCount。
- 有状态组件实现点击计数功能
import React, { Component } from 'react'
export default class Counter extends Component {
constructor(props) {
super(props)
this.state = {
count:0
}
}
render() {
return (
<div>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>计数值为{this.state.count}</button>
</div>
)
}
}
- Hooks后的版本
import React,{useState} from 'react'
export default function CounterFunction() {
const [count, setCount] = useState(0)
return (
<div>
<button onClick={()=>setCount(count+1)}>计数值为{count}</button>
</div>
)
}
2.Effect Hooks
import React,{useState,useEffect} from 'react'
export default function CounterFunction() {
const [count1, setCount1] = useState(0)
const [count2,setCount2] = useState(0)
useEffect(() =>
console.log('每次数据改变都会执行')
)
useEffect(() =>
console.log('count1改变执行')
, [count1])
useEffect(() =>
console.log('只执行一次')
,[])
return (
<div>
<button onClick={() => setCount1(count1 + 1)}>count1加一{count1}</button>
<button onClick={() => setCount2(count2 + 1)}>count2加一{count2}</button>
</div>
)
}
Hooks本质上就是一类特殊的函数,它们可以为你的函数型组件(function component)注入一些特殊的功能。之所以写这篇文章是因为用class来创建react组件时,有一件很麻烦的事情,就是this的指向问题。为了保证this的指向正确,我们要经常写这样的代码:this.handleClick = this.handleClick.bind(this)
,或者是这样的代码:<button onClick={() => this.handleClick(e)}>
。一旦我们不小心忘了绑定this,各种bug就随之而来,很麻烦。还有一个原因就是开发过程中容易搞不清使用哪个React生命周期,我们通常希望一个函数只做一件事情,但生命周期钩子函数里通常同时做了很多事情。比如在componentDidMount中发起ajax请求获取数据,绑定一些事件监听等等。同时,有时候还需要在componentDidUpdate做一遍同样的事情。当项目变复杂后,这一块的代码也变得不那么直观。现在有了Hooks,生命周期可以扔一边儿了。