将API中间件与Redux-Thunk集成

时间:2018-10-03 19:21:09

标签: reactjs redux redux-thunk

这源于this SO Question

我正在尝试将redux-thunk与我的API中间件集成。当前的逻辑流程是这样的:

从组件this.props.onVerifyLogin();调度的操作

=>

动作转到动作创建者,该动作创建者对中间件创建API调用,如下所示:

// imports

const verifyLoginAC = createAction(API, apiPayloadCreator);

export const verifyLogin = () => dispatch => {
  return verifyLoginAC({
    url: "/verify/",
    method: "POST",
    data: {
      token: `${
        localStorage.getItem("token")
          ? localStorage.getItem("token")
          : "not_valid_token"
      }`
    },
    onSuccess: result => verifiedLogin(dispatch, result),
    onFailure: result => dispatch(failedLogin(result))
  });
};

const verifiedLogin = (dispatch, data) => {
  console.log("verifiedLogin");
  const user = {
    ...data.user
  };
  dispatch(setUser(user));
  dispatch({
    type: IS_LOGGED_IN,
    payload: true
  });
};

// failedLogin function

const setUser = createAction(SET_USER);

apiPayloadCreator in utils/appUtils:

const noOp = () => ({ type: "NO_OP" });

export const apiPayloadCreator = ({
  url = "/",
  method = "GET",
  onSuccess = noOp,
  onFailure = noOp,
  label = "",
  isAuthenticated = false,
  data = null
}) => {
  return {
    url,
    method,
    onSuccess,
    onFailure,
    isAuthenticated,
    data,
    label
  };
};

,然后中间件拦截并执行实际的API调用:     //导入     // axios默认配置

const api = ({ dispatch }) => next => action => {
  next(action);
  console.log("IN API");
  console.log("Action: ", action);
  // this is where I suspect it is failing. It expects an action object
  // but is receiving a function (see below for console.log output)
  if (action.type !== API) return;

  // handle Axios, fire onSuccess/onFailure, etc

动作已创建,但它是函数而不是动作创建者(我知道这是针对redux-thunk的)。但是,当我的API去检查action.type时,它不是API,因此它返回,从不实际执行任何操作,包括调用onSuccess函数。我也尝试在applyMiddleware中的api之前添加redux-thunk,但随后没有我的API动作触发。有人可以协助吗?

编辑:

这是API中间件收到的数据:

ƒ (dispatch) {
    return verifyLoginAC({
      url: "/verify/",
      method: "POST",
      data: {
        token: "" + (localStorage.getItem("token") ? localStorage.getItem("token") : "not_valid_toke…

状态更新:

仍然无法使其正常工作。似乎redux-saga也拥有相当不错的关注者,我应该试试吗?

1 个答案:

答案 0 :(得分:0)

我的API正在干扰。我切换到library(dplyr) filter(df, (COL1!="X" & COL2!="X")) 并使其正常工作:

redux-saga