reactjs - 未捕获的类型错误:无法从道具中读取未定义的属性“长度”
问题描述
我堆了这么久。
关于以下代码,当我从状态中获取成员对象时,它不会被识别为数组对象。
所以我从复制文本中编写了 dummy_member,它可以工作并被识别为数组对象。
render() {
const members = this.props.members; // <- Get from state.
console.log(members); //Show Array Object (1)
console.log(members.length); //Error
const dummy_members = [{xx:xxx},..]; // <- Copied & paste text from JSON data on browser from server.
console.log(dummy_members); // Show Array Object (2)
console.log(dummy_members.length); // It shows array length.
两个 console.log 都显示以下结果。
(12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 3, away_team_p1_shots: 20, away_team_p2_score: 4, …}
1: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 1, away_team_p1_shots: 13, away_team_p2_score: 2, …}
2: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 1, away_team_p1_shots: 15, away_team_p2_score: 2, …}
3: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 2, away_team_p1_shots: 15, away_team_p2_score: 3, …}
4: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 6, away_team_p1_shots: 23, away_team_p2_score: 9, …}
5: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 0, away_team_p1_shots: 10, away_team_p2_score: 2, …}
6: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 1, away_team_p1_shots: 12, away_team_p2_score: 1, …}
7: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 1, away_team_p1_shots: 19, away_team_p2_score: 1, …}
8: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 0, away_team_p1_shots: 10, away_team_p2_score: 2, …}
9: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 3, away_team_p1_shots: 16, away_team_p2_score: 4, …}
10: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 0, away_team_p1_shots: 8, away_team_p2_score: 1, …}
11: {away_team_ot_score: 0, away_team_ot_shots: 0, away_team_p1_score: 0, away_team_p1_shots: 8, away_team_p2_score: 1, …}
length: 12
似乎没有错。
我的问题是 members (1) 和 dummy_members (2) 都有相同的控制台日志,但是两者都有不同的结果。来自 props (1) 的成员未被识别为数组。
我想从 this.props.members 中获取成员对象。
谢谢。
解决方案
如果reducer01
不总是包含一个members
数组,那么const members = reducer01.members
将是未定义的,并且members.length
会抛出您观察到的错误。
为了防止未定义,您可以使用console.log(members && members.length)
.
(为了帮助您修复减速器,您必须在问题中共享减速器的代码。)
推荐阅读
- r - R:如何设置 if 语句条件仅在整列等于一个值时触发?
- python - 最快的日期时间到 ISO8601 转换器
- javascript - 使用 v-for 在 vue 中填充多选菜单和选项
- c# - 在 Blazor 中处理引号
- python - 如何让两个条件语句将信息拉到同一列?
- javascript - 全日历调度程序未显示资源:似乎调度程序文件未加载
- c# - 如何通过单击主页中的按钮将数据从第二页传输到第三页
- python - Flask SQLAlchemy 在 DRY 代码中更新用户信息
- css - Wordpress 视频的最大高度?
- swift - Swift 字符串日期,“2015-06-18T17:02:02.614Z”到本地日期