# Hook 简介
react 官网中介绍:Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。
举个例子:
// React 类组件
class Example extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
add = () => {
this.setState({ count: this.state.count + 1 })
}
render () {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.add}>Add</button>
</div>
)
}
}
// 使用 Hooks 编写函数组件
function Example(props) {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={setCount(count => count + 1)}>Add</button>
</div>
)
}
如何将 Redux与Hooks 结合使用
React Redux现在提供了useSelector和useDispatch Hook,可以使用它们代替connect。
useSelector是连接mapStateToProps的替代方法。向其传递了一个函数,该函数使用Redux的存储状态并返回所需的状态。
useDispatch替换connect的mapDispatchToProps。它所做的只是返回store的dispatch方法,因此我们可以手动调用dispatch。
# 类组件使用connect
import React from 'react'
import { connect } from 'react-redux'
import { addCount } from './actions'
export const Count = ({ count, addCount }) => {
return (
<>
<div>Count: {count}</div>
<button onClick={addCount}>Count</button>
</>
);
};
const mapStateToProps = state => ({
count: state.counter.count
});
const mapDispatchToProps = dispatch => {
return {
onAdd: () => dispatch(addCount())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Count);
# 函数组件使用 Hooks 代替 connect
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addCount } from './actions'
export const Count = () => {
const count = useSelector(state => state.counter.count)
const dispatch = useDispatch()
return (
<>
<div>Count: {count}</div>
<button onClick={() => dispatch(addCount())}> Count </button>
</>
)
}