javascript - 在 React 组件之外使用路由信息
问题描述
我正在使用从外部提取的 fetch 函数,以便可以在整个应用程序中使用它。每当我想发出任何 API 请求时,我都会调用这个包装函数。但这里的问题是,每当服务器返回 401,100 或我基本上想重定向到登录页面的任何状态代码时,我都需要处理一个案例。但是我不会在这里获得路由信息,知道如何解决吗?
这个函数看起来像这样:
export module FetchWrapper {
export async function fetchCall(url, type, headers) {
let url = obj.url;
let options = {};
options.method = type;
options.headers = { ...options.headers, ...headers };
const response = await fetch(url, options);
return await response.json();
}
}
任何组件都会像这样使用:
async componentDidMount() {
try {
let response = await FetchWrapper.fetchCall({
url: `/api/fetch/details`,
type: "GET",
headers: { contentType: "application/json" }
});
//on success
} catch (error) {
// error handling
}
}
App.tsx 中的路由定义
<Switch>
<Route exact={true} path="/" component={Start} />
<Route path="/signin" component={SignIn} />
<Route path="/signout" component={SignOut} />
<Route path="/page1" component={Page1} />
<Route path="/page2" component={Page2} />
</Switch>
解决方案
export module FetchWrapper {
export async function fetchCall(history, {url, type, headers}) {
let url = obj.url;
let options: any = {};
options.method = type;
options.headers = { ...options.headers, ...headers };
const response = await fetch(url, options);
if (response.status === 401 || response.status === 100) {
history.replace("/login");
// you can throw error and catch when execute or what you want
} else {
return await response.json();
}
}
}
async componentDidMount() {
try {
let response = await FetchWrapper.fetchCall(history,{
url: `/api/fetch/details`,
type: "GET",
headers: { contentType: "application/json" }
});
//on success
} catch (error) {
// error handling
}
}
再次检查这两个功能
我希望它有效
推荐阅读
- php - 是否可以从 Phalcon 控制器获取渲染视图输出?从单元测试中?
- azure-databricks - 您可以通过在 SQL 中运行“REFRESH TABLE tableName”命令或通过重新创建所涉及的数据集/数据帧来显式地使 Spark 中的缓存无效
- react-admin - 基于相关记录字段的 React Admin Change 字段
- python - 通过 Python 使用单点登录访问 Office365 SharePoint
- java - Quartz CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek 不工作
- java - 自定义 h2 查询中的转义冒号 (':')
- r - 用胶水补零
- spring-boot - Springboot application container cannot connect to redis container
- r - R - 在数据框中显示数据
- r - any recommend for finding the intersection of two continuous variable in r