2017-01-03 66 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並使您的實際意圖不太清晰。