开发者问题收集

未捕获的类型错误:无法从 props 中读取未定义的属性“length”

2019-12-13
75

我堆了好久。

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

因此,我从复制文本编写了 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

似乎没错。

我的问题是成员(1)和 dummy_members(2)具有相同的控制台日志,但两者的结果不同。来自 props(1)的成员未被识别为数组。

我想从 this.props.members 获取成员对象。

谢谢。

1个回答

如果 reducer01 并非始终包含 members 数组,则 const members = reducer01.members 将未定义,并且 members.length 将抛出您观察到的错误。

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

(为了帮助您修复 Reducer,您必须在问题中分享 Reducer 的代码。)

Aprillion
2019-12-13