我有一个 actions.js 文件正在导出这样的操作
export var toggleTodo = (id) => {
return {
type: 'TOGGLE_TODO',
id
}
}
但是当我使用 es6 import 导入它时出现错误
Uncaught TypeError: Cannot read property 'toggleTodo' of undefined
但是当我使用常见的 js require 来要求它时,它工作得很好!有人可以向我解释为什么会发生这种情况,我的意思是我读到这两件事是相同的......有些东西似乎有所不同?
// var actions = require('actions') working
// dispatch(actions.toggleTodo(id));
import actions from 'actions' //not working
dispatch(actions.toggleTodo(id));
有几种不同的形式import
,每个人做的事情略有不同。您正在使用的那个
import actions from 'actions' //not working
用于导入默认导出 https://stackoverflow.com/questions/21117160/what-is-export-default-in-javascript from actions
模块。你可以看到MDN javascript 参考中的完整列表 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.
它不起作用,因为你的action.js
模块可能没有默认导出,并且actions
未定义。
大致对应的形式require
电话是这样的:
import * as actions from 'actions';
它允许您访问所有导出的值作为属性actions
:
dispatch(actions.toggleTodo(id));
或者您可以像这样使用命名导入:
import {toggleTodo} from 'actions';
那么你可以使用toggleTodo
直接地:
dispatch(toggleTodo(id));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)