Dva
antdesignPro中集成了dva.js。dva是对react中操作redux的简化框架
dva将结构分成了三层:
- view
- model
- service
生成model
models/xxx.js
const xxxModel = {
namespace: "xxx",
// state可以是任意类型
state: {
},
reducers: {
},
effects: {
}
}
将model和view连接
连接的目的是可以在view组件中使用对应model中的数据
Component.js
import { connect } from 'umi'
const Component = (props) => {
return (
<div></div>
)
}
export default connect((state) => {
// 这个state中包含了所有的model state.namespace 就是对应model中的state
return {
// 我们这个组件的props中就包含了对应xxx props.xxx 和 props.dispatch
xxx: state.xxx,
}
})(Component)
model中内容的定义
namespace
可以给模块起别名,未来dispatch时需要添加该别名,并且在connect时需要通过namesapce属性获取数据
state
模块中存储的数据
reducers
类似vuex中的mutations,可以对我们对应的数据进行修改
export default {
namespace: 'namespace',
reducers: {
方法名 (state, {payload}) {
return 新的数据 // 这个新的数据就会覆盖原state
}
}
}
// 组件中触发用dispatch({type: 'namespace/方法名', payload: {}})
// effects中触发用put({type: '方法名', payload: {}})
effects
类似vuex中actions,可以在这个里面进行异步操作,但是需要使用* yield语法
*
就是 async- yield 就是 await
export default {
namespace: 'namespace',
effects: {
*effect方法 ({payload}, {call, put}) {
// 如果涉及异步请求 这个参数通过在dispatch通过payload传递
const res = yield call(异步请求函数, 参数)
// 将结果提交给reducer进行state的修改
yield put({
type: 'reducer方法名',
payload: 数据
})
}
},
reducers: {
方法名 (state, {payload}) {
return 新的数据 // 这个新的数据就会覆盖原state
}
}
}