1、命名空间问题(namespace)
- 如Model是这样:
- app.model({
- namespace:'count',
- state:{
- record:0,
- current:0
- },
- reducers:{
- add(state){
- const newCurrent = state.current+1;
- return {
- record:newCurrent>state.record?newCurrent:state.record,
- current:newCurrent
- };
- },
- }
- });
那么访问这里面的state:state.count 访问里面的reducer:dispatch({type:'count/add'}),同时model里面的state和reducer必须和以上的命名一模一样 即state和reducers。
2、使用connect方法将model和组建绑定(注意使用的时候应该使用es6的箭头函数来绑定或者传入一个函数),这样组件就可以使用model里面的数据同时model也可以接受组件dispatch过来的action。
3、异步操作使用es6的生成器*add() {} 和call put Promise等,一般异步操作数据之后,可以使用dispatch再触发reducer来更新数据。
4、监听事件:
subscriptions: {
}
可以在监听事件里面使用dispatch,需要注意的是:action的名称(type)如果是在 model 以外调用需要添加 namespace。
通过 dispatch 函数,可以通过 type 属性指定对应的 actions 类型,而这个类型名在 reducers(effects)会一一对应,从而知道该去调用哪一个 reducers(effects)。
5、通常第一次的还没有数据的时候可以在组件的生命周期内部发起dispatch,或者监听路由(subscriptions)当时这个路由的时候发起dispatch 从而更新model。
6、组件设计(Container Component&&Presentational Component)
Container Component(容器组件):里面不含有状态 只有props
Presentational Component(展示组件): 一般指的是具有监听数据行为的组件,一般来说它们的职责是绑定相关联的 model 数据,以数据容器的角色包含其它子组件
7、一个关联组件和Modal的一个例子
- import React, { Component, PropTypes } from 'react';
- // dva 的 connect 方法可以将组件和数据关联在一起
- import { connect } from 'dva';
- // 组件本身
- const MyComponent = (props)=>{};
- MyComponent.propTypes = {};
- // 建立组件和数据的映射关系 注意state必传 返回的是需要绑定的model
- function mapStateToProps(state) {
- return {...state.data};
- }
- // 关联 model
- export default connect(mapStateToProps)(MyComponent);