【问题标题】:Flow : destructuring. Missing annotation in React/Preact流:解构。 React/Preact 中缺少注释
【发布时间】:2017-04-10 16:19:57
【问题描述】:

刚刚开始使用 Flow,但似乎无法理解它希望我为解构对象(例如 props)添加类型来做什么

render({ count }, { displayHelp }) {

抛出类似的错误

 16:   render({ count }, { displayHelp }) {
              ^^^^^^^^^ destructuring. Missing annotation

当我添加注释时它仍然抱怨

 17:   render({ count: number }, { displayHelp }) {
              ^^^^^^^^^^^^^^^^^ destructuring. Missing annotation

如果有人能指出,我显然在这里遗漏了一些非常简单的东西?

【问题讨论】:

    标签: reactjs flowtype static-typing preact


    【解决方案1】:

    这对我有用

    type Props = {
        counter?: number
    };
    
    const Component = ({counter}: Props) => (
        <div className="App">
            {counter}
        </div>
    );
    

    【讨论】:

      【解决方案2】:

      使用{ count: number } 的问题在于这与destructuring assignment 的ES6 语法冲突,您可以使用{ a: b } = cc 中获取键为a 的值并将其命名为@ 987654326@,即:

      const c = { a: 1 }
      const { a: b } = c
      //b is now a constant with value 1
      

      目前在 Flow 中并没有很好的解决方法,但这似乎有效(尽管它很丑):

      render({...}: { count: number }, { displayHelp }) {
      

      目前最好的方法似乎是创建一个自定义 type 来捕获您的道具:

      type propsForThisComponent = {
        propA: someType
        propB: anotherType
        ...
      }
      

      然后做:

      render(props: propsForThisComponent) {
      

      这会进行类型检查,尽管它会强制您以 props.propName 访问所有道具。

      【讨论】:

      • 我刚试过这个,我得到一个语法错误。你确定这有效吗?
      • 不,那是个错误。这实际上是一个提议的功能。我正在寻找一种实际的方法来让它立即工作,一旦我知道一个好的方法,我会立即编辑。
      • 好吧,我明白了,我应该发现 ES6 冲突。感谢您的帮助!
      【解决方案3】:

      你需要做这样的事情:

      render({count}: {count: number}, {displayHelp}: {displayHelp: boolean}) { ...
      

      很遗憾,我认为没有更简洁的方法可以做到这一点。

      【讨论】:

        猜你喜欢
        • 2017-05-17
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 2011-01-12
        • 2023-03-10
        • 2019-09-07
        相关资源
        最近更新 更多