属性 在 null 中缺失或在 Flow 中未定义
Property is missing in null or undefined in Flow
我正在使用 Flow 和 React,我有一个 class 使用如下状态和道具类型:
type B = {x:number}
type State = {
a: ?B
};
type Props = {}
class MyClass extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
a: null,
};
}
...
myFunction=()=>{
console.log(this.state.a.x)// Flow error here
}
}
流程错误是:无法获取 this.state.a.x
因为未定义中缺少 属性 x
。我的类型定义有什么问题?为什么我应该在我的构造函数中使用 'Props' 类型定义(props: Props) {} ?
?B
表示a
属性等同于B | null | void
。由于您不能执行 null.x
或 undefined.x
Flow 抛出一个有效的异常。为了使您的代码正常工作,您可以更改
console.log(this.state.a.x);
成为
console.log(this.state.a ? this.state.a.x : null);
这样,如果 a
尚未设置为 B
值,它将记录 null
.
或者你可以创建类型 a: B
,但是你需要有一个 B
值作为初始值放入状态,听起来你可能没有那,因为你的示例状态集 a: null
.
我正在使用 Flow 和 React,我有一个 class 使用如下状态和道具类型:
type B = {x:number}
type State = {
a: ?B
};
type Props = {}
class MyClass extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
a: null,
};
}
...
myFunction=()=>{
console.log(this.state.a.x)// Flow error here
}
}
流程错误是:无法获取 this.state.a.x
因为未定义中缺少 属性 x
。我的类型定义有什么问题?为什么我应该在我的构造函数中使用 'Props' 类型定义(props: Props) {} ?
?B
表示a
属性等同于B | null | void
。由于您不能执行 null.x
或 undefined.x
Flow 抛出一个有效的异常。为了使您的代码正常工作,您可以更改
console.log(this.state.a.x);
成为
console.log(this.state.a ? this.state.a.x : null);
这样,如果 a
尚未设置为 B
值,它将记录 null
.
或者你可以创建类型 a: B
,但是你需要有一个 B
值作为初始值放入状态,听起来你可能没有那,因为你的示例状态集 a: null
.