Redux react-redux hooks使用篇

hooks中使用redux

详细参考React-Redux 官方 Hooks 文档说明
前提,在react应用中已经成功注入了redux。(之前已经写过了怎么注入redux的文章)只是在使用上hooks和在calss组件中使用有所区别,hooks中主要使用以下两个react-reudx暴露的方法,就可以在函数组件中获取到store对象,以及dispatch方法

useSelector()

const result : any = useSelector(selector : Function, equalityFn? : Function)

通过传入 selector 函数,你就可以从从 Redux 的 store 中获取 状态(state) 数据。

警告: selector 函数应该是个纯函数,因为,在任意的时间点,它可能会被执行很多次。

useDispatch()

const dispatch = useDispatch() //获取dispatch方法
代码块
import { Button } from 'antd'
import React from 'react'
// import { createHashHistory } from 'history'
import { withRouter } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux' //====================
import aT from '../store/actions/actionEntry' //=========action module
import './login.css'
const per = ['admin', 'editer', 'reader'] //随机权限

function Login(props) {
    const store = useSelector(state => {
        return Object.assign({}, state)
    })
    const dispatch = useDispatch()
    let click = async () => {
        //Math.random()*52 + 1    //现在这个数就 >=1 且 <53
        await dispatch({ type: aT.checkLogin, isLogin: true, permissions: per[Math.floor(Math.random() * 3)] })
        // createHashHistory().push('/index')
        props.history.push({ pathname: store.login_reducer.path })
    }
    return (
        <div style={{
            border: '4px solid white',
            width: '300px',
            padding: '100px 50px',
            textAlign: 'center',
            backgroundColor: 'rgba(0,0,0,0.4)',
            margin: '0 auto',
            position: 'relative',
            top: '300px',
            left: '300px'
        }}>
            <div style={{
                color: 'yellow',
                fontSize: '18px',
                position: 'absolute',
                width: '300px',
                textAlign: 'center',
                top: '10px',
                left: '0'
            }}>登 录 界 面</div>
            <Button onClick={click}>登 录</Button>
        </div>
    )
}
export default withRouter(Login)

自己在实际例子中的使用,简单的页面登录,大致就是这样使用,很简单就可以入手,有问题可以看看我之前写的,注入redux,连着的代码

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值