1、命名空間問題(namespace) [javascript] view plain copy 如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的一個例子 [javascript] view plain copy 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);