Redux代理Type

来源:互联网 发布:淘宝旗舰店申请 编辑:程序博客网 时间:2024/06/01 16:22

在使用redux时,会经常碰到一个问题,触发了action之后,并没有被reducer处理。一个可能原因就是actionType拼写错误。

// actionTypes.jsexport const FETCH_FILE_REQUEST = 'fetch_file_request';export const FETCH_FILE_SUCCESS = 'fetch_file_success';export const FETCH_FILE_FAIL = 'fetch_file_fail';// filesReducer.jsimport {  FETCH_FILE_REQUEST,  FETCH_FILE_SUCESS,  FETCH_FILE_FAIL} from '../actions/actionTypes';const filesReducer = (state = {}, action) => {  switch (action.type) {    case FETCH_FILE_SUCESS:      return { ...state, file: action.payload };    default:      return state;  }}export default filesReducer;

如同上面的例子在reducer中FETCH_FILE_SUCESS 拼写错误,然而并不会抛出任何异常,因此debug会非常费力。

使用Proxy

proxy是ES6引入的新特性,允许我们在对象上定义一些操作

let validator = {  set: function(obj, prop, value) {    if (prop === 'age') {      if (!Number.isInteger(value)) {        throw new TypeError('The age is not an integer');      }      if (value > 200) {        throw new RangeError('The age seems invalid');      }    }    // The default behavior to store the value    obj[prop] = value;    // Indicate success    return true;  }};let person = new Proxy({}, validator);person.age = 100;console.log(person.age); // 100person.age = 'young'; // Throws an exceptionperson.age = 300; // Throws an exception

既然Proxy可以用来校验Object属性是否为指定类型,那么也可以用于保证action的type不为undefined。

由于ES6的模块系统并不支持Proxy所以最终方案如下:

// actionTypes.jsexport const FETCH_FILE_REQUEST = 'fetch_file_request';export const FETCH_FILE_SUCCESS = 'fetch_file_success';export const FETCH_FILE_FAIL = 'fetch_file_fail';// actionTypesProxy.jsexport const {  FETCH_FILE_REQUEST,  FETCH_FILE_SUCCESS,  FETCH_FILE_FAIL,} = require('./actionTypes');// filesReducer.jsimport {  FETCH_FILE_REQUEST,  FETCH_FILE_SUCESS,  FETCH_FILE_FAIL} from '../actions/actionTypesProxy';const filesReducer = (state = {}, action) => {  switch (action.type) {    case FETCH_FILE_SUCESS:      return { ...state, file: action.payload };    default:      return state;  }}
原创粉丝点击