[react-control-center 番外篇1] ant-design-pro powered by C_C

Ant Design Pro Powered by react-control-center

cc版本的ant-design-pro來了,ant-design-pro powered by C_C


咱們先看看redux是如何工做起來的,在來細比較ccredux的最大的不一樣之處

redux如何工做?訂閱redux單一狀態樹裏的部分數據源,讓組件被redux接管,從而實現當訂閱的數據源發生變化時才觸發渲染的目的
  • 咱們知道,在redux世界裏,能夠經過一個配置了mapStateToPropsconnect高階函數去包裹一個組件,可以獲得一個高階組件,該高階組件的shouldComponentUpdate會被redux接管,經過淺比較this.props!==nextProps來高效的決定被包裹的組件是否要觸發新一輪的渲染,之因此可以這麼直接進行淺比較,是由於在redux世界的reducer裏,規定了若是用戶改變了一個狀態某一部分值,必定要返回一個新的完整的狀態,以下所示,是一個傳統的經典的connectreducer寫法示例。
/** code in component/Foo.js, connect現有組件,配置須要觀察的`store`樹中的部分state,綁定`action` */
class Foo extends Component{
  //...
  render(){
    return (
      <div>
        <span>{this.props.fooNode.foo}</span>
        <button onClick={this.props.actions.incFoo}>incFoo</button>
      </div>
    );
  }
}
export default connect(
  state => ({
    list: state.list,
    fooNode: state.fooNode,
  }),
  dispatch => ({
    actions: bindActionCreators(fooActionCreator, dispatch)
  })
)(Foo)

/** code in action/foo.js, 配置action純函數 */
export const incFoo = () =>{
  return {type:'INC_FOO'};
}

/** code in reducer/foo.js, 定義reducer函數 */
function getInitialState() {
  return {
    foo: 1,
    bar: 2,
  };
}

export default function (state = getInitialState(), action) {
  switch (action.type) {
    case 'INC_FOO': {
      state.foo = state.foo + 1;
      return {...state};
    }
    default:{
      return state;
    }
      
  }
}
複製代碼
  • ant-design-prodva世界裏,dvaredux作了一層淺封裝,省去了繁瑣的定義action函數,connect時要綁定action函數等過程,給了一個命名空間的概覽,一個命名空間下能夠定義stateeffectsreducers這些概念,組件內部dispatchaction對象的type的格式形如${namespaceName}/${methodName},這樣dva就能夠經過解析用戶調用dispatch函數時派發的action對象裏的type值而直接操做effects裏的函數,在effects裏的某個函數塊內處理完相應邏輯後,用戶能夠調用dva提供給用戶的put函數去觸發reducers裏的對應函數去合成新的state,儘管流程上簡化了很多,可是歸根到底仍是不能脫離redux的核心理念,須要合成一個新的state! 如下示例是ant-design-pro裏一個經典的變種redux流程寫法.
/** code in component/Foo.js, connect現有組件,配置須要觀察的`store`樹中的部分state */
import { connect } from 'dva';

class Foo extends Component{
  //...
  render(){
    return (
      <div>
        <span>{this.props.fooNode.foo}</span>
        <button onClick={()=>this.props.dispatch({type:'fooNode/incFoo', payload:2})}>incFoo</button>
      </div>
    );
  }
}
export default connect(
  state => ({
    list: state.list,
    fooNode: state.fooNode,
  })
)(Foo)

/** code in models/foo.js */
import logService from '@/services/log';

export default {
  namespace: 'fooNode',

  state: {
    foo: 1,
    bar: 1,
  },

  effects: {
    *query({ payload:incNumber }, { call, put }) {
      yield call(logService, incNumber);
      yield put({
        type: 'saveFoo',
        payload: incNumber,
      });
    },
  },

  reducers: {
    saveFoo(state, action) {
      return { ...state, foo:action.payload };
    },
  },
};

複製代碼
cc如何工做?訂閱react-control-center的部分數據源,當這些部分數據源任意一個部分發生變化時,cc主動通知該組件觸發渲染
  • ccredux最大的不一樣就是,cc接管了全部cc組件的具體引用,當用戶的react組件註冊成爲cc組件時ccregister函數須要用戶配置ccClassKeymodulesharedStateKeysglobalStateKeysstateToPropMapping等參數來告訴cc怎麼對這些具體的引用進行分類,而後cc就可以高效並精確的通知哪些cc組件實例可以發生新一輪的渲染。
  • 實際上當你在cc組件實例裏調用this.setState時,效果和原有的this.setState毫無差異,可是其實cc組件實例的this.setState已近再也不是原來的了,這個函數已經被cc接管並作了至關多的工做,原來的已經被cc保存爲reactSetState,當你調用cc組件實例的this.setState,發生的事情大概通過了如下幾步
  • 由於此文主要是介紹和證實cc 的弱入侵性和靈活性,而ant-design-pro裏的組件的state並不須要被接管,因此咱們下面的示例寫法僅僅使用cc.connect函數將組件的狀態和cc.store打通,這些狀態並不是從state裏取,而是從this.$$propState裏獲取,下面的示例註釋掉的部分是原dva寫法,新增的是cc的寫法.
  • (備註:此處僅僅展現關鍵代碼詳細代碼 )
/** code in src/routes/Dashboard/Analysis.js, */
import React, { Component } from 'react';
// import { connect } from 'dva';
import cc from 'react-control-center';

// @connect(({ chart, loading }) => ({
//   chart,
//   loading: loading.effects['chart/fetch'],
// }))
@cc.connect('Analysis', {
  'chart/*': '',
  'form/*': '', // this is redundant here, just for show isPropStateModuleMode's effect }, { isPropStateModuleMode: true }) export default class Analysis extends Component { state = { loading: true, salesType: 'all', currentTabKey: '', rangePickerValue: [], } componentDidMount() { this.$$dispatch({ module: 'chart', type: 'fetch' }).then(() => this.setState({ loading: false })); // this.props.dispatch({ // type: 'chart/fetch', // }).then(() => this.setState({ loading: false })); } componentWillUnmount() { // const { dispatch } = this.props; // dispatch({ // type: 'chart/clear', // }); // this.$$dispatch({ module: 'chart', type: 'clear' }); } handleRangePickerChange = (rangePickerValue) => { this.setState({ rangePickerValue, }); // this.props.dispatch({ type: 'chart/fetchSalesData'}); this.$$dispatch({ module: 'chart', type: 'fetchSalesData' }); } selectDate = (type) => { this.setState({ rangePickerValue: getTimeDistance(type), }); // this.props.dispatch({ type: 'chart/fetchSalesData' }); this.$$dispatch({ module: 'chart', type: 'fetchSalesData' }); } render() { const { rangePickerValue, salesType, currentTabKey, loading } = this.state; console.log('%c@@@ Analysis !!!', 'color:green;border:1px solid green;'); const { visitData, visitData2, salesData, searchData, offlineData, offlineChartData, salesTypeData, salesTypeDataOnline, salesTypeDataOffline, } = this.$$propState.chart; // } = this.props.chart; } } 複製代碼
  • models的替換
/** 原來的model,code in src/models/chart */
export default {
  namespace: 'chart',

  state: {
    visitData: [],
    visitData2: [],
    salesData: [],
    searchData: [],
    offlineData: [],
    offlineChartData: [],
    salesTypeData: [],
    salesTypeDataOnline: [],
    salesTypeDataOffline: [],
    radarData: [],
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(fakeChartData);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchSalesData(_, { call, put }) {
      const response = yield call(fakeChartData);
      yield put({
        type: 'save',
        payload: {
          salesData: response.salesData,
        },
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setter(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    clear() {
      return {
        visitData: [],
        visitData2: [],
        salesData: [],
        searchData: [],
        offlineData: [],
        offlineChartData: [],
        salesTypeData: [],
        salesTypeDataOnline: [],
        salesTypeDataOffline: [],
        radarData: [],
      };
    },
  },
};

/** cc定義的model,code in src/cc-models/chart  */
function getInitialState() {
  return {
    wow: 'wow',
    visitData: [],
    visitData2: [],
    salesData: [],
    searchData: [],
    offlineData: [],
    offlineChartData: [],
    salesTypeData: [],
    salesTypeDataOnline: [],
    salesTypeDataOffline: [],
    radarData: [],
  }
}

export default {
  module:'',
  state:getInitialState(),
  reducer:{
    callAnotherMethod:function*(){
      return {wow:'changeWowValue'};
    }
    fetch:function*() {
      const response = yield fakeChartData();
      return response;
    },
    //這裏稍作修改,演示了reducer方法內如何調用其餘reducer方法
    fetchSalesData:async function({state, moduleState, dispatch, payload}) {
      console.log(sate, moduleState, payload);
      //這裏的dispatch若是不指定module和reducerModule,就隱含的是由最初的在cc實例裏觸發$$dispatch時計算好的module和reducerModule
      await dispatch({type:'callAnotherMethod'});
      const response = await fakeChartData();
      const salesData = response.salesData;
      return { salesData };
    },
    clear(){
      const originalState = getInitialState();
      return originalState;
    }
  }
}
複製代碼
由上可以發現,cc裏的setState須要的statedispatch對應函數返回的state,都是react鼓勵的部分state,你須要改變哪一部分的state,就僅僅把這一部分state交給cc就行了。同時cc也兼容redux生態的思路,一切共享的數據源都從props注入,而非存儲在state裏。
由於全部的改變state的行爲都會通過$$changeState,因此狀態的變化依然是可預測的同時也是能夠追蹤的,後面cc的迭代版本里會利用immutable.js,來讓狀態樹能夠回溯,這樣cc就能夠實現時間旅行的功能了,敬請期待.

注意哦! 如今我僅僅先把兩個路由級別的組件交給cc處理, ant pro任然完美工做起立, 這兩個路由文件是 routes/Dashboard/Analysis.jsroutes/Forms/Basic.js.
同時我也新增了一個路由組件 routes/Dashboard/CCState.js 來展現cc強大能力, 這個組件尚未完全寫完,將會被持續更新的, 就像 我爲cc專門寫的引導示例同樣,將會很快會爲你們帶來更多的精彩演示

但願我親愛的朋友們花一點時間瞭解react-control-center並探索它更多有趣的玩法

相關文章
相關標籤/搜索