React第一次渲染为何容易出现TypeError: Cannot read property 'XX' of undefined
2019-11-15 00:41
2166 查看
此题可能大家会不屑一顾,哎,错误都给你怼脸上了你还不会嘛,其实大家有没有认真思考过这其中的原因。先上一张错误图,剩余的全靠编。没兴趣看图的老铁们可以拉到最底下直接看结论
错误:
代码:
其次,我再把简化后的代码拉出来遛一遛(可以先跳过图片,去看结论)
奇怪之处:
在作者那行会抛出一开始截图上的错误,注释掉这一行,其余的都能正常运行
原因:
首先我们注意一下 this.state.detail,默认值给的是空字符串。
为什么我要特意说明空字符串呢
大家注意一下下面的代码
上面这张图就是精髓。
this.state.detail.title 第一次渲染实际上访问的是''.title,返回undefined,所以渲染到页面上的是字符串undefined 但是this.state.detail.author.loginname则不同,this.state.detail.author已经是undefined,即相当于undefined.loginname,抛出TypeError错误 结论: 访问空字符串上的属性会返回undefined 访问undefined上的属性会抛出TypeError错误访问null上不存在的属性会破除TypeError错误 要注意从'',null,undefined上获取属性时会产生什么样的结果,防止出现不受控制的结果 解决:
在使用属性前做好兼容,防止抛出错误直接卡死页面
例如:this.state.detail.author.loginname 我们可以改为 this.state.detail.author&&this.state.detail.author.loginname
相关文章推荐
- easyui使用时出现这个Uncaught TypeError: Cannot read property 'combo' of undefined
- Uncaught TypeError: Cannot call method 'replace' of undefined 的解决
- Ckeditor: Uncaught TypeError: Cannot read property 'keyCode' of undefined 解决方法
- vue出现TypeError: Cannot read property '__ob__' of undefined的解决
- cocos2dx通过用eclipse移植android时出现 error: undefined reference to "XXX类:XX()"
- Matlab出现On Startup: Error using eval undefined function 'workspacefunc' for input arguments of type
- easyui使用时出现这个Uncaught TypeError: Cannot read property 'combo' of undefined
- win10 QtCreator5.10 编译opengl出现 error: undefined reference to `_imp__glXXX@XX'
- Uncaught TypeError: Cannot read property 'call' of undefined jquery.validate.min.js:28
- Extjs4---Uncaught TypeError: Cannot call method 'hasOwnProperty' of undefined
- 【StackFlow】Uncaught TypeError: Cannot read property 'pageCount' of undefined
- cocos2dx通过用cygwin移植时出现 error: undefined reference to "XXX类:XX()"
- TypeError: Cannot read property 'parentNode' of undefined
- Uncaught TypeError: Cannot call method 'substring' of undefined
- Matlab出现On Startup: Error using eval undefined function 'workspacefunc' for input arguments of type
- Hbuilder MUI运行出现Uncaught TypeError: Cannot read property '0' of undefined at js/mui.min.js:7
- windows qt 编译opengl出现 error: undefined reference to `_imp__glXXX@XX'
- echarts.min.js:25 Uncaught TypeError: Cannot read property 'features' of undefined 报错解决方法
- Extjs4---Uncaught TypeError: Cannot call method 'substring' of undefined
- Uncaught TypeError: Cannot read property 'call' of undefined jquery.validate.min.js:28