欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Redux代理Type

程序员文章站 2022-03-08 20:49:04
...

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

// actionTypes.js

export const FETCH_FILE_REQUEST = 'fetch_file_request';
export const FETCH_FILE_SUCCESS = 'fetch_file_success';
export const FETCH_FILE_FAIL = 'fetch_file_fail';


// filesReducer.js

import {
  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); // 100
person.age = 'young'; // Throws an exception
person.age = 300; // Throws an exception

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

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

// actionTypes.js
export const FETCH_FILE_REQUEST = 'fetch_file_request';
export const FETCH_FILE_SUCCESS = 'fetch_file_success';
export const FETCH_FILE_FAIL = 'fetch_file_fail';

// actionTypesProxy.js

export const {
  FETCH_FILE_REQUEST,
  FETCH_FILE_SUCCESS,
  FETCH_FILE_FAIL,
} = require('./actionTypes');

// filesReducer.js

import {
  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;
  }
}

相关标签: redux es2015