我何时应该使用带括号的括号 [英] When should I use brackets with imports

查看:152
本文介绍了我何时应该使用带括号的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,第一个是todoHelper.js

I have two file, the first one is todoHelper.js

它有 export const addTodo =(list,item)=> [... list,item]

稍后我要使用 addTodo 在另一个文件中,我只是从'./todoHelpers'进行 import {addTodo}

later on I want to use addTodo in another file, I simply do import {addTodo} from './todoHelpers'

但我也是看到人们做出口默认而不是出口。有什么不同?

But I'm also seeing people doing export default instead of just export. What's the differences?

推荐答案

每个文件只能有一个导出默认值,因此当您执行导出默认值时

You can have only one export default per file and hence when you do export default like

export default AddTodo = (list, item) => [...list, item]

您可以像

import MyAddTodo from './todoHelpers'

由于babel知道您正在尝试访问默认组件,因此您可以通过任何名称在您的文件中访问它

Since babel knows that you are trying to access the default component, you can access it in you file by any name

现在假设你这样做

export const AddTodo = (list, item) => [...list, item]

您可以在文件中有多个此类导出,例如

You can have multiple such exports in you file like

export const AddTodo =(list,item)=> [... list,item]
export const DeleteTodo =(list,item)=> [... list,item]

export const AddTodo = (list, item) => [...list, item] export const DeleteTodo = (list, item) => [...list, item]

当你导入时,你需要对它们进行解构,如

and when you import you will need to destructure them like

import {AddTodo, DeleteTodo}from './todoHelpers'

现在因为你有多个这样的出口因此,如果您使用其他名称访问,如果您访问哪个组件,则不会知道您要访问哪个组件

Now since you have multiple such exports thus babel wont know which component you are tyring to access if you access if by a different name like

import {MyAddTodo, MyDeleteTodo}from './todoHelpers'

如果你想这样做,你必须将它们导入为它是和他们改变他们的名字,如

If you want to do this you will have to import them as it is and them change thier name like

import {AddTodo as MyAddTodo, DeleteTodo as MyDeleteTodo}from './todoHelpers'

一般来说,你将默认出口主要组件和其他你可以正常导出或当你只有一个组件需要从文件导出然后你可以选择你想要的但是一个很好的方法将是 export 默认为。

So as general practice you will default export the main component and the rest you can have as export normally or when you have only one component that you need to export from a file then you can choose whatever you want but a nice way will be to export it as default.

这篇关于我何时应该使用带括号的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆