美文网首页深入浅出Redux系列
13-React Redux与Hooks共同使用

13-React Redux与Hooks共同使用

作者: 钢笔先生 | 来源:发表于2020-01-29 20:59 被阅读0次

Time: 20200129

React Redux Pattern

  • Action Creators
  • Reducers
  • Provide the store
  • Connect the components

组件可以访问状态并且分发行为修改状态。

使用React Hooks,无需使用connect()函数了就可以完成订阅store以及分发(dispatch)动作。

截屏2020-01-29下午8.58.45.png

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.

相关文章

网友评论

    本文标题:13-React Redux与Hooks共同使用

    本文链接:https://www.haomeiwen.com/subject/fbsbthtx.html