How to navigate with react navigation outside react component?

99封情书 提交于 2021-02-11 18:10:17

问题


I'm building a code to check if access_token or refresh_token are valid. I'm using axios interceptors to check the response to generate new token.

How to use navigate(React Navigation) inside axios interceptors?

Error:

09:53:55.852 client_log FarmsList:React.FC -> error [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

     axios.interceptors.response.use(
          (response) => {
            return response
          },
          async (error) => {
            const navigation = useNavigation()
            const originalRequest = error.config
            const accessToken = await getAccessToken()
            const refreshToken = await getRefreshToken()
        if (
          error.response.status === 400 &&
          originalRequest.url === connectTokenUrl &&
          accessToken
        ) {
          removeConnectToken()
          navigation.navigate('SignIn')
          return Promise.reject(error)
        }
    
        if (error.response.status === 401 && !originalRequest._retry) {
          originalRequest._retry = true
          console.log('entrou 401')
          if (!refreshToken) {
            navigation.navigate('SignIn')
            return Promise.reject(error)
          }
    
          const data = {
            grant_type: 'refresh_token',
            client_id: 'xxx',
            refresh_token: refreshToken,
          }
          const formData = new FormData()
          _.forEach(data, (value, key) => {
            formData.append(key, value)
          })
    
          return axios({
            method: 'post',
            url: connectTokenUrl,
            data: formData,
            headers: {'Content-Type': 'multipart/form-data'},
          }).then((response) => {
            const {access_token, refresh_token} = response.data
            connectToken(access_token, refresh_token)
            axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`
            return axios(originalRequest)
          })
        }
        return Promise.reject(error)
      },
    )

回答1:


There are several ways to access the navigation props outside the navigation.

  1. The useNavigation hook : this is used for scenarios where you access the navigation prop from functional components which are under the navigation container. Eg : A navigation button which is inside a screen.

  2. The navigationRef : this is used for scenarios where you access the navigation outside the navigation, used for scenarios like redux middleware.

You should use the navgation ref for this scenario and perform your navigation actions. You can use the RootNavigation.js and call the navigation actions.

import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';

export default function App() {
  return (
    <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
  );
}

// RootNavigation.js

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}



回答2:


where is your navigation param? if you can show me more of your code (your full component) will be helpful, its possible that you are calling some hook outside of your functional component



来源:https://stackoverflow.com/questions/62697017/how-to-navigate-with-react-navigation-outside-react-component

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