在 React 组件之外使用路由信息

Using routing info outside of the React Component

我正在使用提取到外部的提取函数,以便它可以在整个应用程序中使用。每当我想发出任何 API 请求时,我都会调用此包装函数。但这里的问题是,每当服务器 returns 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
    }
  }

再次检查这两个功能

希望有用

使用 "react-router-dom" 中的 "history" 几乎解决了这个问题。

索引文件里面


    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();
        }
    }
}