react dva 的 connect 與 @connect

https://dvajs.com/guide/introduce-class.html#connect-方法html

connect的做用是將組件和models結合在一塊兒。將models中的state綁定到組件的props中。並提供一些額外的功能,譬如dispatchide

 

connect 的使用函數

【connect 方法返回的也是一個 React 組件,一般稱爲容器組件。由於它是原始 UI 組件的容器,即在外面包了一層 State。fetch

connect 方法傳入的第一個參數是 mapStateToProps 函數,該函數須要返回一個對象,用於創建 State 到 Props 的映射關係。】ui

簡而言之,connect接收一個函數,返回一個函數。spa

第一個函數會注入所有的models,你須要返回一個新的對象,挑選該組件所須要的models。code

export default connect(({ user, login, global = {}, loading }) => ({
    currentUser: user.currentUser,
    collapsed: global.collapsed,
    fetchingNotices: loading.effects['global/fetchNotices'],
    notices: global.notices
}))(BasicLayout);

// 簡化版
export default connect( 
  ({ user, login, global = {}, loading }) => {
        return {
          currentUser: user.currentUser,
          collapsed: global.collapsed,
          fetchingNotices: loading.effects['global/fetchNotices'],
          notices: global.notices
        }
  }
)(BasicLayout);

 

@connect的使用component

其實只是connect的裝飾器、語法糖罷了。htm

// 將 model 和 component 串聯起來
export default connect(({ user, login, global = {}, loading }) => ({
    currentUser: user.currentUser,
    collapsed: global.collapsed,
    fetchingNotices: loading.effects['global/fetchNotices'],
    notices: global.notices,
    menuData: login.menuData,         // by hzy
    redirectData: login.redirectData, // by hzy
}))(BasicLayout);



// 改成這樣(export 的再也不是connect,而是class組件自己。),也是能夠執行的,但要注意@connect必須放在export default class前面: // 將 model 和 component 串聯起來 @connect(({ user, login, global = {}, loading }) => ({ currentUser: user.currentUser, collapsed: global.collapsed, fetchingNotices: loading.effects['global/fetchNotices'], notices: global.notices, menuData: login.menuData, // by hzy redirectData: login.redirectData, // by hzy })) export default class BasicLayout extends React.PureComponent { // ... }
相關文章
相關標籤/搜索