Reactjs 空检查仍然抛出流错误
为避免流错误,需要在何处放置空检查的规则是什么?这段代码给出了一个错误,这让我很惊讶:Reactjs 空检查仍然抛出流错误,reactjs,flowtype,Reactjs,Flowtype,为避免流错误,需要在何处放置空检查的规则是什么?这段代码给出了一个错误,这让我很惊讶: // @flow import React, { Component } from "react"; type Props = {| apples: ?Array<Array<string>>, oranges: ?Array<Array<string>>, |}; class FruitBasket extends Component<Pro
// @flow
import React, { Component } from "react";
type Props = {|
apples: ?Array<Array<string>>,
oranges: ?Array<Array<string>>,
|};
class FruitBasket extends Component<Props> {
render() {
if (this.props.oranges == null || this.props.apples == null) {
return null;
}
var dummyVariable = 16;
var apples = this.props.apples.map((ask) => {
return null;
})
var oranges = this.props.oranges.map((bid) => {
return null;
})
return null;
}
}
export default FruitBasket;
/@flow
从“React”导入React,{Component};
类型道具={|
苹果:?阵列,
橙子:?阵列,
|};
类扩展组件{
render(){
if(this.props.oranges==null | | this.props.apples==null){
返回null;
}
var dummyVariable=16;
var apples=this.props.apples.map((ask)=>{
返回null;
})
var oranges=this.props.oranges.map((出价)=>{
返回null;
})
返回null;
}
}
出口默认果篮;
错误是:
无法调用this.props.oranges.map,因为null或未定义的[1]中缺少属性映射。
流编译器在
var apples=…
声明之后会“忘记”空检查,这似乎很愚蠢。这是一个验证/排序问题。Flow不知道this.props.apples.map()的作用,因此从技术上讲,它可能最终设置this.props.oranges=null。由于这可能发生,在调用this.props.oranges.map()
时,如果(this.props.oranges==null)细化不再有效,并且从类型检查器的角度来看,this.props.oranges
可能为null。您有两种解决方案:
- 如果(this.props.oranges==null)返回null,则移动
代码>在调用
this.props.oranges.map()之前选中。不利的一面是,然后你分裂了你的纾困逻辑,最终无缘无故地映射到苹果
- 将这些值分配给临时变量,以便流可以判断它们的类型以后不会更改。这将是我的建议
render() { if (this.props.oranges == null || this.props.apples == null) { return null; } const { oranges, apples } = this.props; var dummyVariable = 16; var applesItems = apples.map((ask) => { return null; }) var orangesItems = oranges.map((bid) => { return null; }) return null; }
this.props.oranges.map()
时,如果(this.props.oranges==null)细化不再有效,并且从类型检查器的角度来看,this.props.oranges
可能为null。您有两种解决方案:
- 如果(this.props.oranges==null)返回null,则移动
代码>在调用
this.props.oranges.map()之前选中。不利的一面是,然后你分裂了你的纾困逻辑,最终无缘无故地映射到苹果
- 将这些值分配给临时变量,以便流可以判断它们的类型以后不会更改。这将是我的建议
render() { if (this.props.oranges == null || this.props.apples == null) { return null; } const { oranges, apples } = this.props; var dummyVariable = 16; var applesItems = apples.map((ask) => { return null; }) var orangesItems = oranges.map((bid) => { return null; }) return null; }