Flow:无法调用`this.state.gameBoard.map`,因为undefined中缺少属性`map`

问题描述 投票:0回答:1
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,因为undefined [1]中缺少属性map。.Flow(InferError)

flowtype
1个回答
4
投票

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

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;
© www.soinside.com 2019 - 2024. All rights reserved.