流:由于未定义属性"map"丢失,因此无法调用"this.state.gameBoard.map" [英] Flow: Cannot call `this.state.gameBoard.map` because property `map` is missing in undefined
问题描述
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>
)
}
}
我不知道为什么它会给我这个错误?
I can't find out why its giving me this error?
确切的错误消息(在.map上):
Exact Error Message (on .map):
无法调用
this.state.gameBoard.map
,因为属性map
为 未定义[1] .Flow(InferError)
Cannot call
this.state.gameBoard.map
because propertymap
is missing in undefined [1].Flow(InferError)
推荐答案
出现错误的原因是,该状态被注释为:
The reason why there is in error is, that state is annotated as:
type State = {
gameBoard?: Array<Array<Connect4Cell>>
}
?
符号表示该值可能未定义.
?
sign is saying to flow that this value might be undefined.
如示例中所示,初始状态已设置,并且包含所需形状的gameBoard
,需要完成的更改是:
As in the example, the initial state is set, and it contains gameBoard
in needed shape, change that needs to be done is:
type State = {
gameBoard: Array<Array<Connect4Cell>>
}
但是,如果在组件运行的任何时间都期望未设置gameBoard
,那么解决方案是在调用.map
函数之前添加检查,如下所示:
However, if at any time of the component live it is expecting to have gameBoard
not set, then the solution will be to add a check before calling .map
function as following
let board = this.state.gameBoard ? this.state.gameBoard.map(row => <Row />) : null;
这篇关于流:由于未定义属性"map"丢失,因此无法调用"this.state.gameBoard.map"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!