1 Module中State值的调用
import React from 'react';
import {connect} from 'dva';
@connect(({ judgeList }) => ({
judgeList,
}))
class JudgeItems extends React.Component {
render() {
const { judgeList } = this.props;// 从 Model中取值
console.log(judgeList);// {correctOption:"true"}
const {correctOption} = judgeList;
return <>
{correctOption}
</>;
}
}
export default JudgeItems;
export default {
namespace: 'judgeList',
state: {
correctOption: "true"
},
reducers: {
save(state, { payload }) {
return { ...state, ...payload } //将接收到的数据 state ,payload 对象展开,合并成新对象进行保存 相当于React 中的SetState方法
},
},
effects: {
},
}
2 Module中方法的调用(effect)
- Effect :处理异步方法
- Reducers:处理同步方法
传入Module中的state
这里进行解构,只使用state中的judgeList的 state用来寻找state的值
调用effects中的那个
带*的函数接收传入的参数
调用effect方法,使用dispatch
import React from 'react';
import {connect} from 'dva';
@connect(({ judgeList }) => ({
judgeList,
}))
class JudgeItems extends React.Component {
render() {
const { judgeList } = this.props;// 从 Model中取值
console.log(judgeList);// {correctOption:"true"}
const {correctOption} = judgeList;
return <>
<button onClick={() => { this.props.dispatch({type: 'judgeList/A',payload: {}})}}>触发model</button>
</>;
}
}
export default JudgeItems;
export default {
namespace: 'judgeList',
state: {
correctOption: "true"
},
reducers: {
save(state, { payload }) {
return { ...state, ...payload }
},
},
effects: {
*A({ payload:{ }}, { call, put, select }){
const { correctOption } = yield select(state => state.judgeList);
console.log("effect",correctOption);// "true"
yield put({ type: 'save', payload: { correctOption } });
},
},
}
3 Module中state变量属性值的改动
import React from 'react';
import {connect} from 'dva';
@connect(({ judgeList }) => ({
judgeList,
}))
class JudgeItems extends React.Component {
handleOptionChange=(a)=>{
console.log(a);
this.props.dispatch({type: 'judgeList/fetchCorrectOption',payload: a})
}
render() {
const {correctOption}= this.props.judgeList;
return <>
<div>{correctOption}</div>
<button onClick={()=>this.handleOptionChange("张三")}>触发model修改correctOption值</button>
</>;
}
}
export default JudgeItems;
export default {
namespace: 'judgeList',
state: {
correctOption: "李四"
},
reducers: {
save(state, { payload }) {
return { ...state, ...payload }
},
},
effects: {
*fetchCorrectOption({ payload: a }, { call, put, select }){
console.log("123456",a);
yield put({ type: 'save', payload: {correctOption:a}});
}
},
}