【问题标题】:Flow: Cannot call `this.state.gameBoard.map` because property `map` is missing in undefined流程:无法调用“this.state.gameBoard.map”,因为未定义中缺少属性“map”
【发布时间】:2019-07-15 19:56:42
【问题描述】:
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) 中缺失

【问题讨论】:

  • 顺便说一下,和直接问题无关,但我觉得这个this.state.gameBoard.map&lt;React.Element&lt;any&gt;&gt;(row =&gt; &lt;Row /&gt;)应该是简单的this.state.gameBoard.map(row =&gt; &lt;Row /&gt;)

标签: flowtype


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多