首页 > 解决方案 > 由于从 index.js 导入需要循环

问题描述

我收到有关我的 react-native 项目的警告:

Require cycles are allowed, but can result in uninitialized values. 
Consider refactoring to remove the need for a cycle.
Require cycle: src/navigation/index.js -> src/navigation/mainDrawerNavigator.js -> src/navigation/index.js

这是因为我有从index.js文件导出一个文件夹内的所有类的习惯,也从指定的index.js文件中导入(这很方便,虽然我不确定是否正确做法,但看起来虽然很常见:这里这里

我有以下目录结构:

src/
   navigation/
      index.js
      mainDrawerNavigator.js
      homeTabNavigator.js
      otherNavigator.js

index.js(我同时导出mainDrawerNavigatorhomeTabNavigator

export {default as HomeTabNavigator} from './homeTabNavigator';
export {default as MainDrawerNavigator} from './mainDrawerNavigator';
export {default as OtherNavigator} from './otherNavigator';

问题在于mainDrawerNavigator我需要homeTabNavigator这样导入它

import { 
    HomeTabNavigator,
    OtherNavigator,
} from '@/navigation';  // this is the source of the warning

有没有办法index.js从不导致导入require cycle

我知道我可以这样导入:

import HomeTabNavigator from './homeTabNavigator';
import OtherNavigator from './otherNavigator';

但是对于某些文件夹,我在index.js文件和文件夹中有很长的导出列表,我不想一个一个地导入(如果可能的话)

标签: javascriptreact-native

解决方案


推荐阅读