2

在一个名为 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

4

1 回答 1

3

您在那里拥有的东西被命名为 exports,而不是解构。

您必须像这样导出它们,而不是作为默认导出

// 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';
于 2017-01-13T17:14:19.160 回答