2017-01-03 41 views
13

我正在写一个小的React Native应用程序,我正在尝试使用Flow,但我无法真正地在任何地方获得适当的教程。如何纠正流程警告:解构(缺少注释)

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

​​

stationJSON响应codelabelstringsJSON内。

如何解决错误/警告?

+0

如果station是JSON响应,也许你必须编写'{'code':code,'label':label}'no? – BNilsou

+0

有'流'我不知道,但在普通的JS React Native是很好的方式。 – jbssm

+0

这是因为ES6类型注释限制的范围。您可以像'... const {code:string,label:string} ...一样指定const的类型...' –

回答

0

为了解构对象,你应该在赋值的右边提供适当的对象结构。在这种特殊情况下,{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);

+0

错误仍然以这种方式相同。但是这个函数已经按照你说的方式调用了,我只需在另一个函数中调用该组件:'',其中'station'是json响应。 – jbssm

16

我会写为

type StationType = { 
    code: String, 
    label: String, 
} 

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

因此,有必要声明该函数接受对象参数的类型。

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) => 
    ... 
如果你想确保 StationDetail总是调用适当的无线电对象,即使当前的实现不仅看起来

station字段。

另一种替代方法是将第一条评论更改为// @flow weak,并让Flow自行推断参数类型。这是Less Good™,因为它可以更轻松地意外地更改公共API并使您的实际意图不太清晰。