rematch常用外掛介紹

supot發表於2019-03-03

外掛系統

rematch實現了一個外掛系統,內建了dispatch和effects兩個外掛,分別用來增強dispatch和處理非同步操作。rematch的外掛,要符合rematch的要求,每個外掛返回一個物件,這個物件可以包含幾個屬性,用來在不同的生命週期中對store進行操作。

對於每一個外掛物件,提供瞭如下幾個屬性進行配置。

  • onInit:進行外掛的初始化工作
  • config: 對rematch進行配置,會在rematch初始化之前,對外掛的config配置進行merge操作
  • exposed:暴露給全域性的屬性和方法,可以理解為佔位符,用於資料的共享
  • middleware:相當於redux的中間鍵,如果提供了這個屬性,會把它交給redux進行處理
  • onModel:載入model的時候會呼叫的方法,用來對model進行處理
  • onStoreCreated:當rematch的store物件生成後,呼叫的方法,生成最終的store物件

rematch常用外掛介紹

DispatchPlugin

plugin包含exposed、onStoreCreated和onModel三個屬性

const dispatchPlugin: R.Plugin = {
	exposed: {
		storeDispatch(action: R.Action, state: any) {
			console.warn('Warning: store not yet loaded')
		},

		storeGetState() {
			console.warn('Warning: store not yet loaded')
		},

		dispatch(action: R.Action) {
			return this.storeDispatch(action)
		},

		createDispatcher(modelName: string, reducerName: string) {
			return async (payload?: any, meta?: any): Promise<any> => {
				const action: R.Action = { type: `${modelName}/${reducerName}` }
				if (typeof payload !== 'undefined') {
					action.payload = payload
				}
				if (typeof meta !== 'undefined') {
					action.meta = meta
				}
				return this.dispatch(action)
			}
		},
	},

	// 在store建立完成的時候呼叫,將增強後的dispatch方法丟擲
	onStoreCreated(store: any) {
		this.storeDispatch = store.dispatch
		this.storeGetState = store.getState
		return { dispatch: this.dispatch }
	},

	// 對model上的每個reducer建立action createor,並掛載到dispatch物件上
	onModel(model: R.Model) {
		this.dispatch[model.name] = {}
		if (!model.reducers) {
			return
		}
		for (const reducerName of Object.keys(model.reducers)) {
			this.validate([
				[
					!!reducerName.match(/\/.+\//),
					`Invalid reducer name (${model.name}/${reducerName})`,
				],
				[
					typeof model.reducers[reducerName] !== 'function',
					`Invalid reducer (${model.name}/${reducerName}). Must be a function`,
				],
			])
			this.dispatch[model.name][reducerName] = this.createDispatcher.apply(
				this,
				[model.name, reducerName]
			)
		}
	},
}
複製程式碼

這個外掛用來處理model的reducers屬性,如果model沒有reducers,就直接退出;否則,遍歷reducers,如果鍵名包含是/符號開頭結尾的或者值不是一個函式,就報錯退出。

通過createDispatcher函式,對每個reducer進行處理,包裝成一個非同步的action creator,action的type由model.name和reducerName組成。

onStoreCreated屬性,會返回增強後的dispatch方法去重置redux預設的dispatch方法。

EffectsPlugin

effects plugin包含exposed、onModel和middleware三個屬性。

const effectsPlugin: R.Plugin = {
	exposed: {
		effects: {},
	},
	
	// 將每個model上的effects新增到dispatch上,這樣可以通過dispatch[modelName][effectName]來呼叫effect方法
	onModel(model: R.Model): void {
		if (!model.effects) {
			return
		}
        
        
        // model的effects可以是一個物件,或者是一個返回物件的函式,這個函式的引數是全域性的dispatch方法
		const effects =
			typeof model.effects === 'function'
				? model.effects(this.dispatch)
				: model.effects

		for (const effectName of Object.keys(effects)) {
			this.validate([
				[
					!!effectName.match(/\//),
					`Invalid effect name (${model.name}/${effectName})`,
				],
				[
					typeof effects[effectName] !== 'function',
					`Invalid effect (${model.name}/${effectName}). Must be a function`,
				],
			])
			this.effects[`${model.name}/${effectName}`] = effects[effectName].bind(
				this.dispatch[model.name]
			)
			this.dispatch[model.name][effectName] = this.createDispatcher.apply(
				this,
				[model.name, effectName]
			)
			// isEffect用來區分是普通的action,還是非同步的,後面的loading外掛就是通過這個欄位來判斷是不是非同步操作
			this.dispatch[model.name][effectName].isEffect = true
		}
	},

	// 用來處理 async/await actions的redux中間鍵
	middleware(store) {
		return next => async (action: R.Action) => {
			if (action.type in this.effects) {
				await next(action)
				// 會把全域性的state作為effect方法的第二個引數傳入
				return this.effects[action.type](
					action.payload,
					store.getState(),
					action.meta
				)
			}
			return next(action)
		}
	},
}
複製程式碼

通過exposed將effects掛載到rematch物件上,用來儲存所有model中的effects方法。

middleware屬性用來定義中間鍵,處理async/await 非同步函式。

onModel用來將所有model的effects方法儲存在dispatch上,並使用'modelName/effectName'的key將對應的effect方法儲存在全域性的effects物件上。

@rematch/loading

對每個model中的effects自動新增loading狀態。

export default (config: LoadingConfig = {}): Plugin => {
	validateConfig(config)

	const loadingModelName = config.name || 'loading'

	const converter =
		config.asNumber === true ? (cnt: number) => cnt : (cnt: number) => cnt > 0

	const loading: Model = {
		name: loadingModelName,
		reducers: {
			hide: createLoadingAction(converter, -1),
			show: createLoadingAction(converter, 1),
		},
		state: {
			...cntState,
		},
	}

	cntState.global = 0
	loading.state.global = converter(cntState.global)

	return {
		config: {
		    // 增加一個loading model,用來管理所有的loading狀態
			models: {
				loading,
			},
		},
		onModel({ name }: Model) {
			// 使用者定義的model如果和注入的loadingmodel重名,則退出這個model
			if (name === loadingModelName) {
				return
			}

			cntState.models[name] = 0
			loading.state.models[name] = converter(cntState.models[name])
			loading.state.effects[name] = {}
			const modelActions = this.dispatch[name]

			// 收集每個model上的effect方法
			Object.keys(modelActions).forEach((action: string) => {
			    // 通過isEffect來判斷是否是非同步方法
				if (this.dispatch[name][action].isEffect !== true) {
					return
				}

				cntState.effects[name][action] = 0
				loading.state.effects[name][action] = converter(
					cntState.effects[name][action]
				)

				const actionType = `${name}/${action}`

				// 忽略不在白名單中的action
				if (config.whitelist && !config.whitelist.includes(actionType)) {
					return
				}

				// 忽略在黑名單中的action
				if (config.blacklist && config.blacklist.includes(actionType)) {
					return
				}

				// 指向原來的effect方法
				const origEffect = this.dispatch[name][action]

				// 對每個effect方法進行包裹,在非同步方法呼叫前後進行狀態的處理
				const effectWrapper = async (...props) => {
					try {
					    // 非同步方法請求前,同步狀態
						this.dispatch.loading.show({ name, action })
						const effectResult = await origEffect(...props)
						
						// 非同步請求成功後,同步狀態
						this.dispatch.loading.hide({ name, action })
						return effectResult
					} catch (error) {
					    // 非同步請求失敗後,同步狀態
						this.dispatch.loading.hide({ name, action })
						throw error
					}
				}

				// 使用包裹後的函式替代原來的effect方法
				this.dispatch[name][action] = effectWrapper
			})
		},
	}
}複製程式碼

這個外掛會在store上增加一個名為loading的model,這個model的state有三個屬性,分別為global、models和effects。

  • global:用來儲存全域性的狀態,只要任意effect被觸發,就會引起global的更新
  • models:它是一個物件,用來表示每個model的狀態,只要是這個model下的effect被觸發,就會引起對應model欄位的更新
  • effects:它是一個物件,以model為單位,記錄這個model下每個effects的狀態,如果某個effect被觸發,會去精確的更新這個effect對應的狀態。

在預設情況下,會遍歷所有model的effects,對每個isEffect為true的action,用一個非同步函式進行包裹,使用try catch捕獲錯誤。

常用的配置項

  • asNumber:預設是false,如果設定為true,那麼狀態就是非同步被呼叫的次數
  • name:loading model的name,預設是loading
  • whitelist:白名單,一個 action 列表,只收集在列表中的action的狀態。命名使用“model名稱” / “action名稱”,{ whitelist: ['count/addOne'] })
  • blacklist:黑名單一個 action 列表,不使用 loading 指示器。{ blacklist: ['count/addOne'] })
store.js

import { init } from '@rematch/core'
import createLoadingPlugin from '@rematch/loading'

// 初始化配置
const loading = createLoadingPlugin({})

init({
  plugins: [loading]
})
複製程式碼
exmaple modle.js

const asyncDelay = ms => new Promise(r => setTimeout(r, ms));
export default {
  state: 0,
  reducers: {
    addOne(s) {
      return s + 1
    }
  },
  effects: {
    async submit() {
      // mocking the delay of an effect
      await asyncDelay(3000)
      this.addOne()
    },
  }
}

複製程式碼
app.js

const LoginButton = (props) => (
  <AwesomeLoadingButton onClick={props.submit} loading={props.loading}>
    Login
  </AwesomeLoadingButton>
)

const mapState = state => ({
  count: state.example,
  loading: {
    global: state.loading.global,                   // true when ANY effect is running
    model: state.loading.models.example,            // true when ANY effect on the `login` model is running
    effect: state.loading.effects.example.submit,   // true when the `login/submit` effect is running
  },
})

const mapDispatch = (dispatch) => ({
  submit: () => dispatch.login.submit()
})

export default connect(mapState, mapDispatch)(LoginButton)
複製程式碼

@rematch/immer

immer 是Mobx作者寫的一個immutable庫,利用ES6的proxy和defineProperty實現js的不可變資料。相比於ImmutableJS,操作更簡單,也不用學習特有的API。

對於一個複雜的物件,immer會複用沒有改變的部分,僅僅替換修改了的部分,相比於深拷貝,可以大大的減少開銷。

對於react和redux,immer可以大大減少setState和reducer的程式碼量,並提供更好的可讀性。

舉個例子,想要修改todoList中某項的狀態,常規的寫法

todos = [
    {todo: 'bbbb', done: true},
    {todo: 'aaa', done: false}
];


state的情況
this.setState({
    todos: [
        ...todos.slice(0, index),
        {
            ...todos[index],
            done: !todos[index].done
        },
        ...todos.slice(index + 1)
    ]
})


reducer的情況
const reducer = (state, action) => {
  switch (action.type) {
    case 'TRGGIER_TODO':
      const { members } = state;
      return {
        ...state,
        todos: [
            ...todos.slice(0, index),
            {
                ...todos[index],
                done: !todos[index].done
            },
            ...todos.slice(index + 1)
        ]
      }
    default:
      return state
  }
}
複製程式碼

如果使用immer,程式碼可以簡化為

import produce from 'immer'

state的情況
this.setState(produce(draft => {
    draft.todos[index].done = !draft.todos[index].done;
))

reducer的情況
const reducer = produce((draft, action) => {
  switch (action.type) {
    case 'TRGGIER_TODO':
      draft.todos[index].done = !draft.todos[index].done;
  }
})
複製程式碼

這個外掛重寫了redux的combineReducers方法,從而支援了immer。

import { Models, Plugin } from '@rematch/core'
import produce from 'immer'
import { combineReducers, ReducersMapObject } from 'redux'

function combineReducersWithImmer(reducers: ReducersMapObject) {
	const reducersWithImmer = {}

	// model的reducer函式必須有返回,因為immer只支援物件型別
	for (const [key, reducerFn] of Object.entries(reducers)) {
		reducersWithImmer[key] = (state, payload) => {
		    // 如果state不是物件,則直接返回reducer的計算值
			if (typeof state === 'object') {
				return produce(state, (draft: Models) => {
					const next = reducerFn(draft, payload)
					if (typeof next === 'object') {
						return next
					}
				})
			} else {
				return reducerFn(state, payload)
			}
		}
	}

	return combineReducers(reducersWithImmer)
}

const immerPlugin = (): Plugin => ({
	config: {
		redux: {
			combineReducers: combineReducersWithImmer,
		},
	},
})

export default immerPlugin
複製程式碼

使用外掛

store.js

import { init } from '@rematch/core'
import immerPlugin from '@rematch/immer';

const immer = immerPlugin();

init({
  plugins: [immer]
})


複製程式碼
model.js

const immerTodos = {
  state: [{
    todo: 'Learn typescript',
    done: true,
  }, {
    todo: 'Try immer',
    done: false,
  }],
  reducers: {
    addTodo(state, payload) {
      state.push(payload);
      return state;
    },
    triggerTodo(state, payload) {
      const { index } = payload;
      state[index].done = !state[index].done;
      return state;
    },
  },
};

export default immerTodos;
複製程式碼

rematch-plugin-default-reducer

對於一般的model而言,reducer的作用就是根據state和action來生成新的state,類似於(state, action) => state,這個plugin的作用是為每個model生成一個名為setValues的reducer。如果是state是一個物件,會對action.payload和state使用Object.assign去進行屬性的合併;如果state是基礎型別,會使用action.payload去覆蓋state。

const DefaultReducerPlugin = {
  onModel(model) {
    const { reducers = {} } = model;

    if (Object.keys(reducers).includes('setValues')) {
      return false;
    }

    reducers.setValues = (state, payload) => {
      if (isObject(payload) && isObject(state)) {
        return Object.assign({}, state, payload);
      }

      return payload;
    };

    this.dispatch[model.name].setValues = this.createDispatcher.apply(
      this,
      [model.name, 'setValues'],
    );
  },
};
複製程式碼

使用

const countModel = {
    state: {
        configList: [],
    },
    effects: {
        async fetchConfigList() {
            const res = await fetch({url});
    
            res && res.list && this.setValues({
                configList: res.list,
            });
        },
    },
};


init

import defaultReducerPlugin from 'rematch-plugin-default-reducer';

const store = init({
    ...
    
    models,
    plugins: [defaultReducerPlugin],
    
    ...
    
});複製程式碼


相關文章