我们通过一个小的计算器来进行学习并实践dispatch(实现功能+1 -1和+上一个传入参数)
一、dispatch方法(+1 -1操作)
首先我们需要用之前学的知识,见上一篇文章https://blog.csdn.net/m0_72694993/article/details/126597160?spm=1001.2014.3001.5501
1.准备工作:运用之前的知识引入connect,在umijx中写入dva,在model中新建一个文件写入state属性值,在首页创建setStateToProps函数取到map,return中输入想要的值传入props中...
以上在上一个文章中都有,接下来我们开始实现计数器的+1-1功能
2.在state中存储当前数值和当前用户
export default{
state:{
count:0,
name:'xxx'
},}
3.在setStateToProps中返回我们想要的数值并取到以及应用
const mapStateToProps= state => {
console.log(state);
return{cout:state.user.count,name:state.user.name};
}
这样我们的props中就有了name 和cout两个属性,然后在页面显示
const HomePage = (props) => {
return (
<div className={styles.container}>
<h1>当前用户为:{props.name}</h1>
<h1>计数器:当前的数值为{props.cout}</h1>
<button onClick={()=>{addOne(props.dispatch)}}>+</button>
<button onClick={()=>{reduceOne(props.dispatch)}}>-</button>
</div>
);
};
4.添加在Module中reduces中写入方法
reducers:{
add(state){
return{
...state,
count:state.count+1
}},
reduce(state){
return{
...state,
count:state.count-1
}
}
}
注意:值得注意的是注意传入参数state,而且返回值直接替代原来的state,不想修改的需要用...state来返回不修改的属性。
6.在主页中写入函数定义和函数绑定,注意的是我们定义函数的时候需要用到dispatch参数,我们需要在props中取到,所以在点击事件中绑定时需要用箭头函数进行绑定,传入props.dispatch,
然后调用dispatch中参数为type:路径/方法函数名字'';
import styles from './index.less';
import { connect } from 'umi';
function addOne(dispatch){
dispatch({type:'user/add'});
}
function reduceOne(dispatch){
dispatch({type:'user/reduce'});
}
const HomePage = (props) => {
return (
<div className={styles.container}>
<h1>当前用户为:{props.name}</h1>
<h1>计数器:当前的数值为{props.cout}</h1>
<button onClick={()=>{addOne(props.dispatch)}}>+</button>
<button onClick={()=>{reduceOne(props.dispatch)}}>-</button>
</div>
);
};
const mapStateToProps= state => {
console.log(state);
return{cout:state.user.count,name:state.user.name};
}
// const mapStateToProps= state=>{
//
// return {name : state.users.user.name };
// }
export default connect(mapStateToProps)(HomePage);
二、额外参数的传入(+10)
1.额外参数的写入,写在type的后边,可以传入多个参数以对象的形式传入
function addTen(dispatch) {
dispatch({ type: 'user/addTen' ,n:10,m:20});
}
function reduceTen(dispatch) {
dispatch({ type: 'user/reduceTen' ,n:10,m:20});
}
2.额外参数的接受,在模块models下定义文件的reducers进行接收,在接收的时候,可以用解构赋值的方式进行接收
addTen(state, { m }) {
return {
...state,
count: state.count + m,
}
},
reduceTen(state, { n }) {
return {
...state,
count: state.count - n,
};
}
就可以愉快的玩耍了