Redux Thunk 共享异步对象

Redux Thunk Sharing Async Object

如果我有以下thunk:

function postReq(body) {
  return dispatch =>
    superagent.post("/files")
              .then(response => dispatch(actionCreator(response)));
}

如何与代码库的其他部分共享超级代理请求对象?我会把它传递到 actionCreate 并将其放入商店吗?

我想中止对某些事件的请求,这就是我寻找这个的原因。

编辑 为手头的问题提供更多背景信息。当用户上传文件时,他可以选择中止上传。当我在 thunk 中创建超级代理请求时,我需要传递请求对象才能调用 superagent.abort().

好吧,首先我想向您介绍一些 ES6 功能,这些功能将使您的代码更具可读性。现在你有:

function postReq(body) {
  return dispatch =>
    superagent.post("/files")
              .then(response => dispatch(actionCreator(response)));
}

首先,您可以使用 ES6 通过 2 个步骤使您的函数更具可读性:

步骤 1

更新您的动作创建器以存储在成本变量中:

const postReq = (body) => {
      return dispatch =>
        superagent.post("/files")
                  .then(response => dispatch(actionCreator(response)));
}

步骤2

您的函数是 returning 函数,因此您可以使用隐式 return:

使其更短且更易读
const postReq = (body) => (dispatch) => {
            superagent.post("/files")
                      .then(response => dispatch(actionCreator(response)));
}

现在,回答你可以尝试做他们在这里公开的事情: https://github.com/reactjs/redux/issues/1461#issuecomment-190165193

适用于您的案例的内容如下:

const postReq = (body) => (dispatch) => {
       superagent.post("/files")
                  .then(response => dispatch(actionCreator(response)));

      const abort = superagent.abort.bind(superagent)
      return { abort }       
}

我自己从未这样做过,但据我所知,它将中止方法绑定到一个变量,该变量将被 returned 并执行存储在那里的函数将在 postReq 上下文中调用中止方法。