【问题标题】:How to correct flow warning: destructuring (Missing annotation)如何纠正流量警告:解构(缺少注释)
【发布时间】:2017-05-17 12:42:22
【问题描述】:

我正在编写一个小型 React Native 应用程序,并且我正在尝试使用 Flow,但我无法在任何地方获得关于它的适当教程。

我不断收到错误:destructuring (Missing annotation) 关于此代码第一行中的({ station })

const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;

stationjson 响应codelabeljson 中是 strings

如何修复错误/警告?

【问题讨论】:

  • 如果站是JSON响应,也许你必须写{'code': code, 'label': label}否?
  • flow 我不知道,但简单来说,JS React Native 就可以了。
  • 这是因为 ES6 类型注解的范围限制。您可以指定 const 的类型,就像 ...const {code:string, label:string}...

标签: javascript reactjs react-native flowtype


【解决方案1】:

我尝试了您的示例并得到了No errors!,因为 Flow 不需要对私有函数进行类型注释。

如果我像这样添加export

// @flow
export const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
  return code + label;
};

我收到以下错误。 (我认为这与您所看到的足够接近。)

Error: 41443242.js:2
  2: export const StationDetail = ({ station }) => {
                                   ^^^^^^^^^^^ destructuring. Missing annotation


Found 1 error

您至少可以通过两种方式解决这个问题。更好的方法是为函数参数添加类型注释。例如:

export const StationDetail =
  ({ station }: { station: { code: number, label: string } }) =>

export const StationDetail =
  ({ station }: {| station: {| code: string, label: string |} |}) =>

甚至

type Code = 1 | 2 | 3 | 4 | 5 | 6;
type Radio ={|
  station: {| code: Code, label: string |},
  signalStrength: number,
  volume: number,
  isMuted: bool,
|};
export const StationDetail = ({ station }: Radio) =>
  ...

如果您想确保始终使用正确的 Radio 对象调用 StationDetail,即使当前实现仅查看 station 字段。

另一种选择是将第一条评论更改为// @flow weak,并让 Flow 自行推断参数类型。 That is Less Good™,因为它可以更容易地意外更改您的公共 API,并使您的实际意图变得不那么清晰。

【讨论】:

    【解决方案2】:

    我会这样写

    type StationType = {
      code: String,
      label: String,
    }
    
    function StationDetail({ station } : {station : StationType}) => {
      const {
        code,
        label,
    } = station;
    

    需要声明函数接受的对象参数的类型。

    【讨论】:

      【解决方案3】:

      为了使对象解构工作,您应该在赋值的右侧提供适当的对象结构。在这种特殊情况下,{station} 作为函数参数(赋值的左侧)应该由类似{station:{code: "stg", label:"stg"}} 的东西提供。确保您使用适当的对象作为参数调用StationDetail 函数。

      var StationDetail = ({ station }) => {
        var {code, label} = station;
        console.log(code,label);
      },
          data = {station: {code: 10, label:"name"}};
      
      StationDetail(data);

      【讨论】:

      • 错误仍然如此。但是这个函数已经被你说的那样调用了,我只是在另一个函数中调用组件:<StationDetail key={station.code} station={station} />,这里station是json响应。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2013-08-02
      • 2014-07-15
      • 1970-01-01
      • 2018-06-24
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多