首页 > 解决方案 > 在 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>


标签: javascriptreactjsasync-awaitreact-routeres6-modules

解决方案


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
    }
  }

再次检查这两个功能

我希望它有效


推荐阅读