`import { useState } from 'react'` 是不是一种解构?

Is `import { useState } from 'react'` kind of destructure or not?

我想说清楚一件事

在React中,我们经常使用import {useState, useEffect} from 'react'

我们可以将其视为 ES6 中的解构功能吗?

没有。 它不像对象解构,但它实际上是导入命名导出。 更清楚地说,它只是导入一个导出为 useState.

的模块

不,它们是不同的。

虽然它们看起来很相似(可能 import 被设计成 看起来像解构 ),但它们的行为方式并不相同。为了明确这一点,importing 使用了稍微不同的语法:使用 as 关键字进行导入重命名,而不是解构中熟悉的 :

这些差异是因为模块系统的工作方式。其他差异是:

  • imported 变量不能被导入模块赋值,然而...

  • 出口商可以随时更改 exported 变量,这也将反映在进口商的变量中,这意味着...

  • 嵌套导入重命名是不可能的,就像通过解构如何实现一样:

    import {foo as {bar as baz}} from './module'; 
    //is invalid, as is:
    import {foo as {bar: baz}} from './module'; 
    //...while:
    
    const {foo: {bar: baz}} = value; 
    //is valid.
    
  • 由于模块系统是静态的(如变量),因此无法导入动态密钥或使用 rest 语法(所有导入在 之前评估代码)。

正在查看反应 src code

export {
  useState,
  // ...
  Children,
  // ....
} from './src/React';

因此您可以直接从此对象导入,例如

import { useState } from 'react'
// you can also rename it to anything you want
import { useState as useReactState } from 'react'

或者您可以将整个对象作为默认导出,然后引用其 useState

import React from 'react'

// use React.useState
// renaming will be like assigning a function to another variable e.g.
const useReactState = React.useState

// you also get all exported types and modules and wrap them up in React name 
import * as React from 'react'

Babel 转译输出

import React from 'react'
const Component = () => {
    const [state, setState] = React.useState()
}
// will transpile to something like
var Component = function Component() {
  var _React$useState = _react["default"].useState(),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      state = _React$useState2[0],
      setState = _React$useState2[1];
};

另一方面

import {useState} from 'react'
const Component = () => {
    const [state, setState] = useState()
}
// will transpile to something like
var Component = function Component() {
  var _useState = (0, _react.useState)(),
      _useState2 = _slicedToArray(_useState, 2),
      state = _useState2[0],
      setState = _useState2[1];
};

对象销毁和import/export声明有一些相似之处,但它们最终并不相同,两者都有各自不同的特定特征

ES6 in-depth | Export Statement | Import Statement