首页 > 解决方案 > 未捕获的类型错误:无法从道具中读取未定义的属性“长度”

问题描述

我堆了这么久。

关于以下代码,当我从状态中获取成员对象时,它不会被识别为数组对象。

所以我从复制文本中编写了 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 中获取成员对象。

谢谢。

标签: reactjsjsx

解决方案


如果reducer01不总是包含一个members数组,那么const members = reducer01.members将是未定义的,并且members.length会抛出您观察到的错误。

为了防止未定义,您可以使用console.log(members && members.length).

(为了帮助您修复减速器,您必须在问题中共享减速器的代码。)


推荐阅读