import { useState } from 'react'` 是否属于解构?

Ade*_*nut 5 javascript destructuring ecmascript-6 es6-modules

我想澄清一件事。

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

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

Ami*_*imi 0

查看react src代码

export {
  useState,
  // ...
  Children,
  // ....
} from './src/React';
Run Code Online (Sandbox Code Playgroud)

所以你可以直接从这个对象导入,例如

import { useState } from 'react'
// you can also rename it to anything you want
import { useState as useReactState } from 'react'
Run Code Online (Sandbox Code Playgroud)

或者您可以获取默认导出的整个对象,然后引用它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'
Run Code Online (Sandbox Code Playgroud)

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];
};
Run Code Online (Sandbox Code Playgroud)

另一方面

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];
};
Run Code Online (Sandbox Code Playgroud)

对象销毁和导入/导出语句有一些相似之处,但最终并不相同,两者都有各自不同的特点

ES6 深入| 出口声明| 进口声明