React使用DVA本地state传值取值


最近在用Ant Pro 做一个后台系统,在使用中发现Antd Pro使用DVA来实现redux+sagas+router一系列的功能,比传统方式要方便快捷的多,自己研究了其中一些原理,在此贴上代码供别人参考也给自己做个记录,

需要取值的页面

index.js

import { connect } from 'dva';

//这里是一个语法糖,和传统的connect()()作用一样。即把对应models目录下的state取出与本页的变量关联。
@connect(({ chart, loading, global = {} }) => ({    //其中global={}表示global中的所有state
  chart,   //等同chart:chart,ES6语法。 
  weather: global.weather,   //读取原有的state,即models中的global.js文件中的weather
  city: global.city
  loading: loading.effects['chart/fetch'],   //这个statu使用models中的chart.js文件中的fetch方法异步获取
}))
export default class XXX extends Component {
...
render(){
 const { chart, loading, weather, city } = this.props;  //在这可用'this.props'读取

}
}

含有state值的页面

chart.js

export default {
  namespace: 'chart',

  state: {
   ......
  },

  effects: {  //这里相当于是redux
    *fetch(_, { call, put }) {
      const response = yield call(fakeChartData);  //这里的fakeChartData是一个request请求
      yield put({
        type: 'save',
        payload: response,
      });
    },
    ......    
  },
}

global.js

export default {
  namespace: 'global',
  state: {
    collapsed: true,
    notices: [],
    city: "郑州市",
    weather: {},
    mapView: "city",
  },
  .......
}