Redux react-redux hooks使用篇
hooks中使用redux
详细参考 前提,在react应用中已经成功注入了redux。(之前已经写过了怎么)只是在使用上hooks和有所区别,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,连着的代码