如果我有以下 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 分两步使您的函数更具可读性:
步骤1
更新您的动作创建者以存储在成本变量中:
const postReq = (body) => {
return dispatch =>
superagent.post("/files")
.then(response => dispatch(actionCreator(response)));
}
第2步
您的函数正在返回一个函数,因此您可以通过隐式返回使其更短且更具可读性:
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 }
}
我自己从未这样做过,但据我所知,它将 abort 方法绑定到一个将返回的变量,并执行存储在那里的函数将调用 postReq 上下文中的 abort 方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句