2017-10-28 73 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更容易。

相关问题