【问题标题】:Using routing info outside of the React Component在 React 组件之外使用路由信息
【发布时间】:2020-04-26 18:01:49
【问题描述】:

我正在使用从外部提取的 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>


【问题讨论】:

    标签: javascript reactjs async-await react-router es6-modules


    【解决方案1】:

    使用“react-router-dom”中的“历史”几乎可以解决它。

    索引文件内

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

    【讨论】:

      【解决方案2】:
      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
          }
        }
      

      再次检查这两个功能

      我希望它有效

      【讨论】:

      • 你会在组件中获得它作为道具
      • 可以componentDidmount访问历史吗?
      • @Man 是的。如果我尝试使用 this.props.history 并用 withRouter 包装组件
      • 我猜你正在使用 v3 路由,这就是它可能的原因
      猜你喜欢
      • 2011-10-06
      • 2017-09-08
      • 2016-09-15
      • 2017-04-24
      • 2021-01-04
      • 2020-12-27
      • 1970-01-01
      • 2016-12-29
      • 2018-09-10
      相关资源
      最近更新 更多