gpt4 book ai didi

reactjs - 使用 thunk 中间件从非 React 组件调度异步 redux 操作

转载 作者:行者123 更新时间:2023-12-03 14:28:21 24 4
gpt4 key购买 nike

我正在构建一个 React/Redux Web 应用程序,我在其中使用服务来进行所有 API 调用。每当 API 返回 401 - Unauthorized 时我想向我的 redux 存储发送一个注销操作。

现在的问题是我的 api-service 不是 React 组件,所以我无法获取 dispatch 的引用或actions 。我首先做的是导出商店并调用 dispatch手动,但正如我在这里读到的 How to dispatch a Redux action with a timeout?这似乎是一种不好的做法,因为它要求商店是单例,这使得很难在服务器上进行测试和渲染,因为我们需要为每个用户提供不同的商店。

我已经在使用react-thunk ( https://github.com/gaearon/redux-thunk )但我不知道 t see how I can inject Dispatch` 到非 React 组件中。

我需要做什么?或者从 react 组件外部分派(dispatch) Action 通常是一种不好的做法?这就是我的api.services.ts现在看起来像:

... other imports
// !!!!!-> I want to get rid of this import
import {store} from '../';

export const fetchWithAuth = (url: string, method: TMethod = 'GET', data: any = null): Promise<TResponseData> => {
let promise = new Promise((resolve, reject) => {
const headers = {
"Content-Type": "application/json",
"Authorization": getFromStorage('auth_token')
};
const options = {
body: data ? JSON.stringify(data) : null,
method,
headers
};
fetch(url, options).then((response) => {
const statusAsString = response.status.toString();
if (statusAsString.substr(0, 1) !== '2') {
if (statusAsString === '401') {
// !!!!!-> here I need to dispatch the logout action
store.dispatch(UserActions.logout());
}
reject();
} else {
saveToStorage('auth_token', response.headers.get('X-TOKEN'));
resolve({
data: response.body,
headers: response.headers
});
}
})
});
return promise;
};

谢谢!

最佳答案

如果您使用的是 redux-thunk,则可以从操作创建者返回一个函数,该函数具有 dispatch 参数:

const doSomeStuff = dispatch => {
fetch(…)
.then(res => res.json())
.then(json => dispatch({
type: 'dostuffsuccess',
payload: { json }
}))
.catch(err => dispatch({
type: 'dostufferr',
payload: { err }
}))
}

另一个选择是使用中间件进行远程操作。这是这样工作的,中间人可以测试一个 Action 的类型,然后将其转换为一个或多个其他 Action 。看看here ,它是相似的,即使基本上是关于动画的,答案也以一些关于如何使用中间件进行远程请求的解释结束。

关于reactjs - 使用 thunk 中间件从非 React 组件调度异步 redux 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43369009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com