导入的对象在函数外部未定义

时间:2018-08-07 09:37:20

标签: javascript react-native

我有一个FunctionalModule类,它代表我的React-Native应用程序的一部分(所有这些FunctionalModules使用ReactNavigation在传统的底部导航栏中显示为选项卡)。

我的所有FunctionalModule实例都需要一些配置常量(其名称,其Redux reducer的名称,其所有操作的前缀,其主要组件等)

这是我的课程:

// moduleTool.ts
/**
 * All specs to define functional module
 */

export function toSnakeCase(camelCase: string) {
  /* ... */
}

export default class FunctionalModule {
  public name: string;
  public actionPrefix: string;
  public reducerName: string;
  public mainComp: React.ComponentType;

  public constructor(name: string, mainComp: React.ComponentType) {
    this.name = name;
    this.actionPrefix = toSnakeCase(name).toUpperCase();
    this.reducerName = name;
    this.mainComp = mainComp;
  }

  public getLocalState(globalState) {
    return globalState[this.reducerName];
  }

  public createActionType(type: string) {
    return this.actionPrefix + "_" + type;
  }
}

我只是通过这种方式构建FunctionalModule的实例:

// homeworkModule/index.ts
// That just export a FunctionalModule instance
import FunctionalModule from "../infra/moduleTool";
import mainComp from "./navigator"; // a React Navigation tabNavigator

export default new FunctionalModule("homework", mainComp);

最后,我想从其他文件(如其精简器)访问其属性,但有一个我不理解的问题。查看评论:

// actions/selectedDiary.ts
/**
 * Diary selected action(s)
 * Build actions to be dispatched to the diary selected reducer.
 */
import homeworkModule from "..";

import { Action } from "redux";
import { fetchHomeworkTasksIfNeeded } from "./tasks";

console.warn(homeworkModule);

// ERROR : homeworkModule is undefined here
export const actionTypeDiarySelected = homeworkModule.createActionType(
  "DIARY_SELECTED"
);

// Expected behaviour
// export const actionTypeDiarySelected = "HOMEWORK_DIARY_SELECTED";

export interface IActionDiarySelected extends Action {
  diaryId: string;
}

export const createActionDiarySelected: (
  diaryId: string
) => IActionDiarySelected = diaryId => ({
  diaryId,
  type: actionTypeDiarySelected
});

export function homeworkDiarySelected(diaryId: string) {
  // OK : Works fine here strangely
  console.warn(homeworkModule.createActionType("DIARY_SELECTED"));
  return dispatch => {
    dispatch(createActionDiarySelected(diaryId));
    dispatch(fetchHomeworkTasksIfNeeded(diaryId));
  };
}

export default homeworkDiarySelected;

因此,在selectedDiary.ts中,导入的homeworkModule在文件全局范围中不可用,但在homeworkDiarySelected函数中。你知道为什么吗?

谢谢! :)

0 个答案:

没有答案