Redirect to screen from an api interceptor (outside of component) in React Native

蓝咒 提交于 2020-01-14 08:44:11

问题


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).

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

回答1:


Follow official document: Navigating without the navigation prop

try something like this

// 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,
};



回答2:


No , you dont need Redux for this. if you are using React Navigation you can do like this way. you can access from everywhere

https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html




回答3:


For this functionality, I think that you need to use Redux




回答4:


Here is a simple medium article that describe redux with redux saga. https://medium.com/@tkssharma/understanding-redux-react-in-easiest-way-part-1-81f3209fc0e5

Use redux-saga as middleware and make use generator function new feauture in es6




回答5:


you can use this way:

import Component_1 from 'PATH TO IT'
import Component_2 from 'PATH TO IT'

this.state = {   
        status: 1
    }


render(){
    if(this.state.status == 1){
          return( <Component_1 onChange={(value)=> this.setState({status: value}) }/> )//Point => A
    }else if(this.state.status == 2){ 
             return( <Component_2 /> )
    }

here we use two component as child of one parent,in Point A we pass a function to child (called props) that give us ability to change state of parent inside of child,based on our work,and when the state is changed component_1 will be unmounted and component_2 will be mount ( login page for example). in component_1 we can use that function in props to change page like this:

if (response.status === 401) {
  deviceStorage.removeData('token');
  // TODO:
  this.props.onChange(2) // here you can redirect to that component
}


来源:https://stackoverflow.com/questions/54232213/redirect-to-screen-from-an-api-interceptor-outside-of-component-in-react-nativ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!