7

I have a actions.js file that is exporting actions like this

export var toggleTodo = (id) => {
  return {
    type: 'TOGGLE_TODO',
    id
  }
}

but when i import it using es6 import i get error

Uncaught TypeError: Cannot read property 'toggleTodo' of undefined

but when i require it using common js require it works just fine! Can someone explain to me why is this happening, I mean i read these two are same things... Something seem to be different ?

// var actions = require('actions') working 
// dispatch(actions.toggleTodo(id));

import actions from 'actions' //not working
dispatch(actions.toggleTodo(id));
4

1 回答 1

11

有几种不同的形式import,每一种做的事情都略有不同。你正在使用的那个

import actions from 'actions' //not working

用于从模块导入默认导出。actions您可以 在 MDN javascript 参考中查看完整列表

它不起作用,因为您的action.js模块可能没有默认导出,并且actions未定义。

大致对应require调用的形式是这样的:

import * as actions from 'actions';

它允许您访问所有导出的值作为以下属性actions

dispatch(actions.toggleTodo(id));

或者您可以像这样使用命名导入:

import {toggleTodo} from 'actions';

那么你可以toggleTodo直接使用:

dispatch(toggleTodo(id));
于 2016-11-23T22:09:53.240 回答