对于react hook已经是久仰大名了,大家都说现在要全面拥抱react hook,那到底hook是个什么东西,它能干什么呢
1.拥有了hook,就不需要写Class了,所有的组件都变成Function
2 拥有了hook,可以先舍弃生命周期钩子函数了
先来看看一个简单的有状态组件
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
render() {
return (
<div>
<p>点击按钮次数:{this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click
</button>
</div>
)
}
}
看起来逻辑还是很清晰的,但当业务变得复杂的时候,组件就会变得非常复杂且难以维护,还有当组件嵌套过多时,props的传递也变得麻烦起来了,当然此时可以使用redux来解决一些问题,但是redux的使用会再次加大项目的复杂度,而且需要严格的按照标准编写组件和redux。
接下来看看上面的计数组件怎么用hook来编写
import { useState } from 'react'
function Test() {
const [count, setCount] = useState(0)
return (
<div>
<p>点击按钮次数: {count}</p>
<button onClick={() => setCount(count + 1)}>
Click
</button>
</div>
)
}
代码中的useState就是一个hook,它只有一个参数,就是初始值,这里就是定义一个state为count,更改这个值的函数为setCount,初始值赋值为0,每次点击按钮触发setCount函数使count值加一。
在一个组件中可以多次使用state hook:
function ManyStatesTest() {
const [age, setAge] = useState(22)
const [name, setName] = useState('Mike')
const [sex, setSex] = useState('male')
// ...
}
接下来再看一个例子:
import { useState, useEffect } from 'react'
function Example() {
const [count, setCount] = useState(0)
// 类似componentDidMount 和 componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`
})
return (
<div>
<p>点击按钮次数: {count}</p>
<button onClick={() => setCount(count + 1)}>
Click
</button>
</div>
)
}
这里出现了一个新的hook:Effect hook,effect的意思是影响,作用。
我们之前已经在 React 组件中执行过数据获取、订阅或者手动修改过 DOM等操作。我们统一把这些操作称为“副作用”,或者简称为“作用”。
现在Effect hook它就是为函数增加这些作用,我们可以在这个hook中获取数据、操作DOM。
在Effect hook中我们可以访问到组件的 props 和 state。
有时候我们需要清除这些“作用”。要实现这一点,useEffect 函数需返回一个清除函数。以下就是一个创建订阅清除订阅的例子:
useEffect(() => {
const subscription = props.source.subscribe()
return () => {
// 清除订阅
subscription.unsubscribe()
}
})
同样的我们也可以使用多个Effect hook。