2017-10-28 58 views
0

我得到一個流錯誤,下面的代碼,我很確定如何解決它。我得到的錯誤是:對象類型(此類型與undefined(太少的參數,預期的默認/休息參數)不兼容)

[flow] object type (This type is incompatible with undefined (too few arguments, expected default/rest parameters)) 
type Props = { 
    levels: { 
     image: string; 
     name: string; 
     description: string; 
     slug: string; 
     value: number; 
    }[]; 
} 

這裏是我的代碼:

// @flow 
// @jsx h 
import { h, Component } from 'preact'; 

// Components 
import Level from '../components/Level'; 

type Props = { 
    levels: Array<{ 
    image: string, 
    name: string, 
    description: string, 
    slug: string, 
    value: number, 
    }> 
}; 

type State = {} 

class Levels extends Component<Props, State> { 
    onclick =() => { /* ... */ } 

    render({ levels }: Props) { 
        ^^^^^ <-- Error here 
    return (
     <div> 
     <ul> 
      {levels.map(level => <Level {...level} />)} 
     </ul> 
     </div> 
    ); 
    } 
} 

export default Levels; 

錯誤消息是有點混亂,因爲它說incompatible with undefined。我已經定義了道具。

我在做什麼錯?

+1

準確的類型定義從反應類型定義擴展。作爲'render'參數訪問道具不支持反應,並且流假定它始終未定義。考慮將props作爲一個實例屬性來訪問,就像這樣:'this.props.levels.map(...)'。既反應又準確支持這一點,它將保持流暢的快樂。 – mpontus

回答

0

固定是這樣的...

class Levels extends Component<Props> { 
    onclick =() => { /* ... */ } 

    render(props: Props | void) { 
    return (
     <div> 
     <ul> 
      {props && props.levels.map(level => <Level {...level} />)} 
     </ul> 
     </div> 
    ); 
    } 
} 

從手動下頁解釋了原因:https://flow.org/en/docs/types/arrays/#toc-array-access-is-unsafe

我無法使用:render({ levels }: Props | void)因爲流動抱怨levels可能爲空。我發現使用props更容易。

相關問題