React Native TypeError:undefined is not an object
发布日期:2022-04-05 00:52:17 浏览次数:1 分类:博客文章

本文共 2153 字,大约阅读时间需要 7 分钟。

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

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
{ render() { return (
{this.props.userBaseVo ? this.props.userBaseVo.userName : ''}
); }}

 

备注:

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,且都不能参与数值运算 详解:

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

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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:React Native 实现垂直水平居中(justifyContent、alignItems)
下一篇:React Native 自定义动态标签

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月16日 07时27分11秒