React Native - 在目录中动态列出/需要文件

时间:2016-10-06 16:50:07

标签: javascript react-native redux react-redux

我正在使用Redux,并希望动态地将所有文件包含在目录中。

/redux/index.js

// Actions

import * as authActions from './auth/authActions';
import * as deviceActions from './device/deviceActions';
import * as globalActions from './global/globalActions';
import * as menuActions from './menu/menuActions';
... etc

export const actions = [
  authActions,
  deviceActions,
  globalActions,
  menuActions,
...
];

// Reducers

import auth from './auth/authReducer';
import device from './device/deviceReducer';
import global from './global/globalReducer';
import menu from './menu/menuReducer';
...

import { combineReducers } from 'redux';

export const rootReducer = combineReducers({
  auth,
  device,
  global,
  menu,
...
});

在上面(简化)示例中,所有文件都具有以下结构:

/redux/
  /auth/
    authActions.js
    authReducer.js
  /device/
    deviceActions.js
    deviceReducer.js
  /global/
    globalActions.js
    globalReducer.js
  /menu/
    menuActions.js
    menuReducer.js
  ...

在这个index.js文件中,如果我可以动态读取redux目录中的所有目录,并动态地要求动作和缩减器导出,那么维护起来会容易得多。

在常规节点环境中,我会做类似的事情(未经测试,但说明了示例):

import fs from 'fs'
import path from 'path'
import { combineReducers } from 'redux'

let actions = []
let reducers {}

fs
  .readdirSync(__dirname).filter((file) => {
    // Only directories
    return fs.statSync(path.join(__dirname, file)).isDirectory();
  })
  .forEach((module) => {
    const moduleActions = require(path.join(__dirname, module, `${module}Actions.js`);
    const moduleReducer = require(path.join(__dirname, module, `${module}Reducer.js`);

    actions.push(moduleActions)
    reducers[module] = moduleReducer.default
  });

export actions
export const rootReducer = combineReducers(reducers)

问题在于fs模块不能反应原生,能够动态地遍历代码库中的目录。有react-native-fs,但这是为了实际访问设备上的文件系统(在编译应用程序之后)[我认为?]。上面比单独要求所有动作和减少器更清晰,并在actions数组和reducer对象中指定它们。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

react-native不支持动态加载模块。所有的javascript文件都捆绑在一个js文件中。