流程:无法调用“ this.state.gameBoard.map”,因为未定义的属性“ map”丢失了

时间:2019-02-21 19:37:40

标签: flowtype

type Color = "Blue" | "Red" | null

type Connect4Cell = {
    state: number,
    color: Color
}

type State = {
    gameBoard?: Array<Array<Connect4Cell>>
}

class Game extends React.Component<{||}, State> {

    state = {
        gameBoard: [
            [{}, {}, {}, {}, {}], 
            [{}, {}, {}, {}, {}], 
            [{}, {}, {}, {}, {}], 
            [{state: 1, color: "Blue"}, {state: 1, color: "Red"}, {state: 1, color: "Blue"}, {state: 1, color: "Red"}, {state: 0, color: null}]
        ]
    }

    render() {

        let board = this.state.gameBoard.map<React.Element<any>>(row => <Row />)

        console.log(this.state)
        return (
            <div>
                <p>This line comes from the render of class, Game. </p>
                <table>
                    <tbody>
                        {board}
                    </tbody>
                </table>
                <Cell />
                <Row />
            </div>
        )
    }

}

我不知道为什么它会给我这个错误?

确切的错误消息(在.map上):

  

无法调用this.state.gameBoard.map,因为属性map是   未定义[1] .Flow(InferError)

中缺少

1 个答案:

答案 0 :(得分:2)

出现错误的原因是,该状态被注释为:

type State = {
    gameBoard?: Array<Array<Connect4Cell>>
}

?符号表明该值可能未定义。

如示例中所示,初始状态已设置,并且包含所需形状的gameBoard,需要完成的更改是:

type State = {
    gameBoard: Array<Array<Connect4Cell>>
}

但是,如果在组件运行的任何时间都希望未设置gameBoard,则解决方案是在调用.map函数之前添加检查,如下所示:

let board = this.state.gameBoard ? this.state.gameBoard.map(row => <Row />) : null;