Javascript 在React组件外部使用路由信息
我正在使用一个从外部提取的fetch函数,以便可以在整个应用程序中使用它。每当我想发出任何API请求时,我都会调用这个包装器函数。但这里的问题是,每当服务器返回401100或任何我基本上想重定向到登录页面的状态代码时,我都需要处理一个案例。但是我在这里没有路由信息,你知道怎么解决吗 此函数如下所示:Javascript 在React组件外部使用路由信息,javascript,reactjs,async-await,react-router,es6-modules,Javascript,Reactjs,Async Await,React Router,Es6 Modules,我正在使用一个从外部提取的fetch函数,以便可以在整个应用程序中使用它。每当我想发出任何API请求时,我都会调用这个包装器函数。但这里的问题是,每当服务器返回401100或任何我基本上想重定向到登录页面的状态代码时,我都需要处理一个案例。但是我在这里没有路由信息,你知道怎么解决吗 此函数如下所示: export module FetchWrapper { export async function fetchCall(url, type, headers) { let url =
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();
}
}
任何组件都会使用如下方式:
App.tsx中的路由定义
再次检查这两个功能
我希望它能工作使用“react router dom”中的“history”几乎解决了这个问题
在索引文件中
你将在componentcan componentDidmount访问历史记录中获得它作为道具?@是的,是的。如果我尝试使用this.props.history并使用WithRoute包装组件,我猜您使用的是v3路由,这就是为什么可能的原因
async componentDidMount() {
try {
let response = await FetchWrapper.fetchCall({
url: `/api/fetch/details`,
type: "GET",
headers: { contentType: "application/json" }
});
//on success
} catch (error) {
// error handling
}
}
<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
}
}
import { Router } from "react-router-dom";
import { createBrowserHistory } from "history";
export const history = createBrowserHistory();
ReactDOM.render(
<Router history={history}>
<App />
</Router>,
document.getElementById("root")
);
import { history } from "../../index";
export module FetchWrapper {
export async function fetchCall(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");
} else {
return await response.json();
}
}
}