【问题标题】:How is this type annotation working in React code without TypeScript?这种类型注释如何在没有 TypeScript 的 React 代码中工作?
【发布时间】:2019-02-20 10:35:14
【问题描述】:

我在 ReactRouter 页面上查看this code example,这篇文章很有趣:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

component: Component 部分看起来像一个类型注释。当我将此示例放入一个空文件时,Webstorm 没有抱怨,但我没有看到它们使用 Flow 或 TypeScript 或导入中的任何内容。

JavaScript 已经有类型注解了吗?当我搜索时,我在 MDN 上没有看到任何关于此的内容,而且 React 也不会自动提供我所学到的类型注释......

【问题讨论】:

  • 这是 ES6 别名,所以它是一个有效的 Javascript

标签: javascript reactjs react-router


【解决方案1】:

您看到的不是类型注释,而是对象模式中的属性。让我们简化您的示例以帮助了解发生了什么。

这是一个容易理解的函数:

f = (h) => [h.x, h.y]

函数f 接收一个对象h 并返回一个包含h.xh.y 的数组。现在在现代 JavaScript 中,不必传入一个对象并在函数体中将其全部分解。相反,我们将函数的参数部分设为 pattern,这样我们就完全不需要处理 h 变量了。所以我们可以像这样重写它(以类似于你的例子的方式):

f = ({x: xValue, y: yValue}) => [xValue, yValue]

因此,就像以前一样,您可以将任何具有 x 和 y 属性的对象传递给 f,它会返回这些属性的值数组。

它在行动:

> f = (h) => [h.x, h.y]
[Function: f]
> f({x:1, y:2, z:3})
[ 1, 2 ]
> f = ({x: xValue, y: yValue}) => [xValue, yValue]
[Function: f]
> f({x:1, y:2, z:3})
[ 1, 2 ]

顺便说一句,通常人们会跳过xValueyValue 部分并拥有:

f = ({x: x, y: y}) => [x, y]

由于简写的属性符号只是:

f = ({x, y}) => [x, y]

但正如@BhojendraRauniyar 在另一个答案中所写,在使用此代码的框架中有大写约定。

【讨论】:

    【解决方案2】:

    这不是类型注释。这是一个名为 destructuring rest parameters 的 ES6 功能:

    首先考虑这个例子:(解构赋值)

    const test = myObject.prop
    // prop can be assigned in a variable
    const { prop } = myObject
    // but we want prop as a test variable
    // and can be written as
    const { prop: test } = myObject
    // which is similar to first line
    console.log(test)
    

    这是我们可以传递参数的方式:

    ({ component, ...rest })
    
    // We're giving component name as Component
    
    ({ component: Component, ...rest })
    

    因此,您可以使用&lt;Component /&gt;,因为您知道小写组件&lt;component /&gt; 在反应中无效。


    此外,我建议您深入研究以下博客:

    Hackernoon: Understanding the destructuring assignment

    JavaScript Info: Destructuring assignment

    Codeburst: Destructuring assignment the complete guide

    Dev.to: Destructuring assignment - array

    Dev.to: Destructuring assignment - object

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 2020-09-03
      • 2012-10-02
      • 2019-03-20
      • 2016-07-23
      • 2016-12-27
      • 2022-01-26
      • 2018-06-10
      相关资源
      最近更新 更多