react-create-app中的对象分解

问题描述 投票:2回答:1

这个问题已经在这里有了答案:

在名为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 }

有人可以解释一下为什么会这样吗? 我做错了吗?

我正在使用:

›创建反应应用-V 1.0.3

javascript reactjs ecmascript-6 babel create-react-app
1个回答
3
投票

您所拥有的称为出口 ,而不是销毁。

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

// 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导入时,关键字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';
© www.soinside.com 2019 - 2024. All rights reserved.