[英]Redux Thunk Sharing Async Object
如果我有以下重击:
function postReq(body) {
return dispatch =>
superagent.post("/files")
.then(response => dispatch(actionCreator(response)));
}
如何与代码库的其他部分共享超级代理请求对象? 我可以将其传递到actionCreate并将其放入商店吗?
我想在某些事件上中止请求,这就是我要寻找的原因。
编辑为手头的问题提供更多背景信息。 用户上载文件时,他可以选择中止上载。 当我在thunk中创建superagent请求时,我需要传递请求对象以能够调用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 }
}
我自己从未做过此事,但据我所知,它将中止方法绑定到一个变量,该变量将被返回,执行存储在其中的函数将在postReq上下文中调用中止方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.