本文介绍了从React Native中的api拦截器(组件外部)重定向到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个React Native应用程序,该应用程序使用JWT令牌对请求进行身份验证.为此,我创建了axios请求和响应拦截器,以将令牌添加到每个请求(请求拦截器),并在响应具有401 HTTP状态(响应拦截器)时将用户重定向到登录屏幕.

I am working on a React Native application that authenticates requests with JWT tokens. For this purpose i have created axios request and response interceptors to add the token to each request (request interceptor) and redirect the user to the login screen whenever a response has 401 HTTP status (response interceptor).

问题是我还没有找到在组件外部进行重定向的方法.下面的代码在API服务中,每当我希望进行API调用时,都会导入该服务.

The problem is that i haven't found a way to do the redirect outside of a component. The code below is in an API service that is imported whenever i want an API call to be made.

由于该服务是无状态的,并且不在乎它从哪个组件调用,我该怎么做才能重定向到登录屏幕?

What do i need to do to redirect to my login screen since this service is stateless and doesn't care what component it is called from?

// Response interceptor
axiosInstance.interceptors.response.use(
  response => {
    // Do something with response data
    if (response.status === 401) {
      deviceStorage.removeData('token');
      // TODO:
      // Redirect to login page
    }
    return response;
  },
  error => {
    // Do something with response error
    return Promise.reject(error);
  }
);

推荐答案

遵循官方文档:在没有导航道具的情况下进行导航

尝试这样的事情

// App.js

import { createStackNavigator, createAppContainer } from 'react-navigation';
import NavigationService from './NavigationService';

const TopLevelNavigator = createStackNavigator({ /* ... */ })

const AppContainer = createAppContainer(TopLevelNavigator);

export default class App extends React.Component {
  // ...

  render() {
    return (
      <AppContainer
        ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }}
      />
    );
  }
}

// NavigationService.js

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

这篇关于从React Native中的api拦截器(组件外部)重定向到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 11:25