[我是redux的新手。因此,在阅读了很多教程之后,我了解到,redux需要redux thunk通过返回另一个函数来调度异步操作。但是,如果我在自定义中间件中调用http请求,那么
2。Redux定制中间件是否没有副作用?我的意思是不需要返回另一个函数。
如果我使用redux thunk,则我的动作创建者看起来像这样。我理解
function incrementAsync() {
return (dispatch) => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment());
}, 1000);
};
}
我对定制中间件感到困惑。
https://blog.logrocket.com/managing-asynchronous-actions-in-redux-1bc7d28a00c6/
根据此博客
const httpMiddleware = store => next => action => {
if (action[HTTP_ACTION]) {
const actionInfo = action[HTTP_ACTION];
const fetchOptions = {
method: actionInfo.verb,
headers: actionInfo.headers,
body: actionInfo.payload || null
};
next({
type: actionInfo.type + "_REQUESTED"
});
fetch(actionInfo.endpoint, fetchOptions)
.then(response => response.json())
.then(data => next({
type: actionInfo.type + "_RECEIVED",
payload: data
}))
.catch(error => next({
type: actionInfo.type + "_FAILED",
payload: error
}));
} else {
return next(action);
}
}
它们没有在action内部返回任何调度函数。我知道store,next,action是内部函数。
任何人都可以帮助我了解这一点。谢谢。
redux-thunk
是一个简单的redux中间件,用于检查您的操作是否为函数并相应地执行操作。您可以在5分钟内自行构建。看看它是source code。