React Native TypeError:undefined is not an object

某些情况下组件内直接取实体属性会报如下错误

TypeError:undefined is not an object(evaluating 'this.props.userBaseVo.userName')

此时就需要用三目?: (this.props.userBaseVo ? this.props.userBaseVo.userUrl : '' )容错,

表示的含义是如果userBaseVo对象存在,才取userUrl字段的值,否则返回空字符串

UserBaseVo

export interface UserBaseVo {
  userId: number;
  userName: string;
  userUrl: string;
}
ComponentUserView
复制代码
export interface IProps extends IBasePageProp {
    userBaseVo: UserBaseVo,
}

export default class ComponentUserView extends React.Component<IProps> {

    render() {
        return (
            <View>
                <Image style={style.item_left_img} source={{ uri: this.props.userBaseVo ? this.props.userBaseVo.userUrl : '' }} />
                <Text style={style.item_name} numberOfLines={1}>{this.props.userBaseVo ? this.props.userBaseVo.userName : ''}</Text>
            </View>


        );
    }
}
复制代码

备注:

1、三目运算再次参与条件判断时要注意优先级()

A:用局部变量临时存储结果

let showStatus = this.props.evaVoList ? this.props.evaVoList.showStatus : null
        if (showStatus == 3) {

B:使用优先级()

if ((this.props.evaVoList ? this.props.evaVoList.showStatus : null) == 3) {

 2、数组、字符串、数值三目的几种写法

字符串:

this.props.abilitys ? this.props.abilitys.categoryName : ''

数组:

let ability = this.props.abilitys ? this.props.abilitys.ability : []

数值:

let showStatus = this.props.evaVoList ? this.props.evaVoList.showStatus : 0

三者''、[]、0明确的指明了类型,但三者都可以(数值只做逻辑判断,不参与数值运算)使用undefined或者null替代

此时临时变量类型就在原来类型上添加了undefined或者null类型,例如string变为string | undefined或者string | null

在做逻辑判断时undefined或者null都表示false

数值类型在参与数值运算时只能默认给明确数值,参与逻辑判断时可以使用undefined或者null,尽量不使用具体数值(包括0),因为逻辑上的数值可能也代表了业务含义,最好使用undefined,因为null数值转换后是0,而undefined是NaN,虽然两者在相等比较(==)时不会转换类型,可以正常使用,因为undefined或者null与任何类型对比结果都是false,且都不能参与数值运算 详解:React Native undefined和null

上述三种写法也是涉及组件内实体直接取值的容错写法,但是有时直接取值也不会出错,需要时可以这样写

state

let evaVoList = this.state.data.evaVoList
        if (evaVoList && evaVoList.length) {

之所以不使用以下容错

let evaVoList = this.state.data?this.state.data.evaVoList:[]
        if (evaVoList && evaVoList.length) {

是因为state下的data一定会初始化(不初始化直接报错),换言之一定存在,所以不需要容错处理,

但取值到再下一级时就需要考虑容错了

this.state.data.selfIdeaVo ? this.state.data.selfIdeaVo.because : ''

综上所述:

props某些情况下取到第二级就需要考虑容错,state第二级不需要容错,第三级才需要


this.props.abilitys ? this.props.abilitys.categoryName : ''

this.state.data.evaVoList

this
.state.data.selfIdeaVo ? this.state.data.selfIdeaVo.because : ''
原文地址:https://www.cnblogs.com/lijianyi/p/14886408.html