Javascript 流类型检查:未定义不是函数,即使存在条件
我正在使用JavaScript代码作为静态类型检查器,出现以下错误:Javascript 流类型检查:未定义不是函数,即使存在条件,javascript,reactjs,flowtype,Javascript,Reactjs,Flowtype,我正在使用JavaScript代码作为静态类型检查器,出现以下错误: 无法调用this.props.onChange,因为未定义的[1]不是函数。 [1] 25│ onChange?:时间=>任何, : 192│ if(isValid&&this.props.onChange){ 193│ 常量匹配=此.matchValue(值); 194│ 如果(匹配){ 195│ this.props.
无法调用this.props.onChange,因为未定义的[1]不是函数。
[1] 25│ onChange?:时间=>任何,
:
192│ if(isValid&&this.props.onChange){
193│ 常量匹配=此.matchValue(值);
194│ 如果(匹配){
195│ this.props.onChange(this.parsedToTime(this.parseValue(match));
196│ }
197│ }
198│ }
我对道具的定义如下(定义了更多道具,标记为…
):
然后,我在React类定义中将props用作类型参数:
export default class TimeInput extends React.Component<Props, State> {
...
// ...and in this class I have a method that calls onChange
// if onChange is not evaluated as false
handleChange = ({ target }: { target: { value: string } }) => {
const { value } = target;
const isValid = this.validateInput(value);
this.setState({
value,
isValid
});
if (isValid && this.props.onChange) {
const match = this.matchValue(value);
if (match) {
this.props.onChange(this.parsedToTime(this.parseValue(match)));
}
}
};
}
导出默认类TimeInput扩展React.Component{
...
//…在这个类中,我有一个调用onChange的方法
//如果onChange未计算为false
handleChange=({target}:{target:{value:string}})=>{
常量{value}=目标;
const isValid=this.validateInput(值);
这是我的国家({
价值
有效
});
if(isValid&&this.props.onChange){
常量匹配=此.matchValue(值);
如果(匹配){
this.props.onChange(this.parsedToTime(this.parseValue(match));
}
}
};
}
如果我正确理解了,那么If(this.props.onChange){…}
测试应该足以让流理解,onChange
不能是未定义的
,因此它必须是一个函数(如类型定义中所定义的)
我在这里做错了什么?直到flow docs,尤其是在调用之前,您应该检查
if(this.props.onChange)
另外,我假设指定
defaultProps
类似于onChange:()=>{}
,因为在调用回调之前得到的检查较少。谢谢,这很有效。我将研究defaultProps
,这似乎非常有用。
export default class TimeInput extends React.Component<Props, State> {
...
// ...and in this class I have a method that calls onChange
// if onChange is not evaluated as false
handleChange = ({ target }: { target: { value: string } }) => {
const { value } = target;
const isValid = this.validateInput(value);
this.setState({
value,
isValid
});
if (isValid && this.props.onChange) {
const match = this.matchValue(value);
if (match) {
this.props.onChange(this.parsedToTime(this.parseValue(match)));
}
}
};
}