【问题标题】:Is `import { useState } from 'react'` kind of destructure or not?`import { useState} from 'react'` 是不是一种解构?
【发布时间】:2020-12-28 10:16:45
【问题描述】:

我想澄清一件事。

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

我们可以认为这是 ES6 中的一个解构特性吗?

【问题讨论】:

标签: javascript ecmascript-6 es6-modules destructuring


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    不,它们是不同的。

    虽然它们看起来很相似(可能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.
      
    • 由于模块系统是静态的(如变量),因此无法导入动态键或使用其余语法(所有导入在评估代码之前已知)。

    【讨论】:

      【解决方案3】:

      看反应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

      【讨论】:

        猜你喜欢
        • 2019-07-02
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        • 2021-09-19
        • 1970-01-01
        相关资源
        最近更新 更多