美文网首页
react native 在非 React 组件的地方访问导航

react native 在非 React 组件的地方访问导航

作者: 王宣成 | 来源:发表于2023-11-13 14:37 被阅读0次

navigationRef.js

// navigationRef.js

import React from 'react';

export const navigationRef = React.createRef();

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

App.js

// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './components/navigationRef';  // 这里是你的 navigationRef 文件的路径

const App = () => {
  return (
    <NavigationContainer ref={navigationRef}>
      {/* ... 其他导航配置 ... */}
      {/* 这里是你的导航组件 */}
    </NavigationContainer>
  );
};

export default App;

其他文件

// baseApi.js

import { navigationRef } from './navigationRef';  // 这里是你的 navigationRef 文件的路径

// ... 其他代码 ...

instance.interceptors.response.use(
  async (response) => {
    // ...
    if (data.status === 0) {
      const code = data.Data.Code;
      switch (code) {
        case '-8':
          console.log('请登录');
          removeItem();
          navigationRef.current?.navigate('Login');  //跳转到登录页
          break;
        // 其他 case ...
      }
    }
    // ...
  },
  // ...
);

相关文章

网友评论

      本文标题:react native 在非 React 组件的地方访问导航

      本文链接:https://www.haomeiwen.com/subject/ihkdwdtx.html