redux 封装分析

387 阅读1分钟

1 reducer.js

1, reducer主要是对react-thunk的reducer的再封装 重写combinceReducer

const config = {
 // fetch 代表异步action
  fetch: ['getConfig'],
  state: {
    data: {
      system_info: { 
        version: "1.2"
      }
    }
  },
  reducers: {
    getConfigSuccess(state, payload) {
      return {
        ...state,
        data: payload
      }
    }
    reset (state) {
      return deepCloneObj(state)
    }
  }
}

通过 combinceReducer({config}) 转化为一个数组,

resultActions = [
    {
      name: "/config/getConfig",
      fn: "处理/config/getConfig的函数"
    },
    {
      name: "/config/getConfigSuccess",
      fn: "处理/config/getConfigSuccess的函数"
    },
    {
      name: "/config/getConfigFailed",
      fn: "处理/config/getConfigFailed的函数"
    }
  ];

然后就是在返回真正的处理函数

// 如果当收到dispatch action的请求,在数组中找到相应的处理函数处理
  return (state = inititalState, action) => {
    // 异步请求action处理
    const actionFn = resultActions.find(cur => cur.name === action.type);
    if (actionFn) {
      return actionFn.fn && actionFn.fn(state, action.payload);
    }
    return state;
  };

这是异步的,如果不是异步,就没有必要写fetch,按照正常处理就可以了

2 公共空间

因为在redux-thunk中,action的type在reducer中和action生成函数中都是一样的,所以提取到了一个公共的对象里边保存

比如上面的 "/config/getConfigSuccess", 就是保存在公共对象里边

{
  "/config/getConfigSuccess": "_config_getConfigSuccess"
}

这样在action的处理函数里边就可以调用公共空间来发起请求了

3 action

action很简单,就是通过函数把真正的redux-thunk的action异步请求包装一下,然后从公共对象里边拿到type,发起请求就可以

dispatch({
     type: Namespace.get(namespace),
     payload
   })