Redux之useSelector、useDispatch
React Redux 从 v7.1.0 开始支持 Hook API 并暴露了 useDispatch 和 useSelector 等 hook。以替代 Redux connect(),减少代码
useSelector
替代mapStateToProps
,从store中提取state数据useDispatch
替代mapDispatchToProps
,从store中获取dispatch方法的引用
类组件中connect(mapStateToProps, mapDispatchToProps)
的使用方法:(传送门)
import { Component } from 'react';
import { connect } from 'react-redux';
class List extends Component {
render() {
return (
<div>
<label htmlFor="input">输入内容</label>
<input id="input" type="text" value={this.props.myValue} onChange={this.props.changeInput} />
</div>
);
}
}
// 把state数据映射到props中
// 这样在jsx中就可以用this.props.myValue来代替this.state.myValue获取值
const mapStateToProps = state => {
return {
myValue: state.myValue,
};
};
// 把store.dispatch()挂载到props上
// 这样在jsx中就可以用this.props.changeInput来代替store.dispatch()改变store里的数据
const mapDispatchToProps = dispatch => {
return {
changeInput(e){
const action = {
type: 'change_input',
value: e.target.value,
};
dispatch(action);
}
};
};
// List是 UI 组件,VisibleList 就是由 React-Redux 通过connect方法自动生成的容器组件。
export const VisibleList = connect(mapStateToProps, mapDispatchToProps)(List);
函数式组件中利用 useSelector
、useDispatch
等HooksApi替代connect(mapStateToProps, mapDispatchToProps)
的使用方法:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
export const List = () => {
const myValue= useSelector(state => state.myValue); // 从store中提取state数据
const dispatch = useDispatch(); // 从store中获取dispatch方法的引用
const changeInput = (e) => {
const action = {
type: 'change_input',
value: e.target.value,
};
dispatch(action);
}
return (
<div>
<label htmlFor="input">输入内容</label>
<input id="input" type="text" value={myValue} onChange={changeInput} />
</div>
);
}
不用写一堆繁琐的 connect
、mapStateToProps
、mapDispatchToProps
了,直接使用 hook函数 对 redux 全局数据进行操作。
超级简单 ~
超级舒服 ~
本文作者:猫老板的豆
本文链接:https://www.cnblogs.com/bingcola/p/16195817.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步