javascript - React-create-app 中的对象解构

标签 javascript reactjs ecmascript-6 babeljs create-react-app

在一个名为index.js的文件中,我有以下导出:

export default {
  foo: true,
  bar: false
}

稍后在文件 home.js 中我将执行以下操作:

import { foo, bar } from './index'

console.log(foo, bar) -> undefined, undefined

如果我导入所有内容,例如:

import index from './index'

console.log(index) -> { foo: true, bar: false }

有人可以解释一下为什么会发生这种情况吗?我做错了什么吗?

我正在使用:

› create-react-app -V 1.0.3

最佳答案

你拥有的有named exports ,而不是解构。

您必须将它们原样导出,而不是 default export :

// this will export all of the defined properties as individual
// named exports, which you can pick-and-choose when importing
// using a similar syntax to destructuring
const foo = true, bar = false;
export {
  foo,
  bar
}

// imported exports named 'foo' and 'bar'
import { foo, bar } from './my-file'.

如果您指定 default 导出,则当您不带大括号导入时,关键字 default 后面的任何内容都将被导出:

// this exports an object containing { foo, bar } as the default export
export default {
  foo: true,
  bar: false
}

// imported without {}
import objectContainingFooBar from './my-file';

关于javascript - React-create-app 中的对象解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639945/

相关文章:

javascript - 如何在 React 中将变量从一个方法传递到另一个方法

reactjs - 如何用 Jest 覆盖 mapDispatchToProps 中的行?

javascript - ES6 类继承可以转换为等效的 ES5 代码吗?

javascript - 从数组中返回具有相同键和值的对象

javascript - 带有手动控件的 slider 不会自动播放 - 可能是 setInterval 行为的问题?

javascript - 从 StencilJS 到 Angular 的事件发射器

reactjs - 为什么react中的 "lifting state up"并不总是有效?

javascript - 未捕获的 TypeError : (0 , _module) 不是一个函数

javascript - 在 Firebug 中哪里可以找到 PIE.htc?

javascript - 连接第一个和最后一个列表元素以创建轮播的幻灯片中的 Jquery 列表?