13-React Redux与Hooks共同使用
2020-01-29 本文已影响0人
钢笔先生
Time: 20200129
React Redux Pattern
- Action Creators
- Reducers
- Provide the store
- Connect the components
组件可以访问状态并且分发行为修改状态。
使用React Hooks,无需使用connect()
函数了就可以完成订阅store
以及分发(dispatch)动作。

Time: 20200129
useSelector Hook
这是react-redux
提供的Hooks。
代码如下:
import React from 'react'
import { useSelector } from 'react-redux'
import { buyCake } from '../redux'
function HooksCakeContainer() {
const numOfCakes = useSelector(state => state.numOfCakes)
return (
<div>
<h2>Num of cakes - {numOfCakes}</h2>
</div>
)
}
export default HooksCakeContainer
useSelector
是一个能够访问store
状态的Hook,此Hook接收一个selector
函数作为参数。
A hook to access the redux store's state. This hook takes a selector function as an argument. The selector is called with the store state.
This hook takes an optional equality comparison function as the second parameter that allows you to customize the way the selected state is compared to determine whether the component needs to be re-rendered.
使用useSelector
就不用通过mapStateToProps
了。
Time: 20200129
useDispatch Hook
此Hook可以得到一个store的dispatch函数的reference.
整个应用本身就一个store
。
代码如下:
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { buyCake } from '../redux'
function HooksCakeContainer() {
const numOfCakes = useSelector(state => state.numOfCakes)
const dispatch = useDispatch()
return (
<div>
<h2>Num of cakes - {numOfCakes}</h2>
<button onClick={() => dispatch(buyCake())}>Buy Cake</button>
</div>
)
}
export default HooksCakeContainer
使用useDispatch
就可以不用mapDispatchToProps
了。
在Redux中使用官方提供的Hooks,详情参考:https://react-redux.js.org/api/hooks
END.