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