【问题标题】:Nested array in object returns 'undefined' when accessing in JSX在 JSX 中访问时,对象中的嵌套数组返回“未定义”
【发布时间】:2021-08-02 15:27:29
【问题描述】:

我是 React 新手,遇到了一些关于如何访问对象内部嵌套数组的问题。我想要做的是在从另一个文件导出的数据对象中呈现“名称”对象。

但是,当我尝试访问嵌套在对象内的数组时,我不断收到“未定义”错误。

当我尝试只打印对象时,我得到了预期的结果。同样,当我尝试访问 Render 函数之外的数组时,它可以工作,但由于某种原因,我不明白它不能在 render 函数内部工作。

我的猜测是我不理解 React 中的对象/数组。

我也尝试过使用 .map,但结果是一样的。

关于我不理解的任何线索?

代码如下:

import React from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import {data} from './RandomData';

export default class Building extends React.Component {

    constructor(){
        super();
        this.state = {
            isLoaded: false,
            selectedBuilding: '',
            housingData:{}
        }
    }

    componentDidMount(){
       this.timeoutId = setTimeout(() => {
        this.setState({
            isLoaded: true,
            error: null,
            housingData: data,
            selectedBuilding: data.buildings[0].name
        } );   
       } ,3000);
        
    }
    
    componentWillUnmount(){
        clearTimeout(this.timeoutId);
    }


    render(){
        const loading = (<h1>loading...</h1>);
        const loadingComplete = (
                <Row>
                    <Col>{this.state.housingData ? <h1>{this.state.housingData.buildings[0].name}</h1> : ''}</Col>
                </Row>
        );

        return (
             <Container fluid>{this.state.isLoaded ? loadingComplete : loading}</Container>
        )
    }
}

RandomData.js:

export const data = {buildings :
    [
    {
        name: "something1",
        id: 1,
        members: 
        {
            id: 1,
            firstName: "Hans",
            lastName: "Ottoson",
            personNumber: 198703259715
        }
    },
    {
        name: "something2",
        id: 2,
        members: 
        {
            id: 1,
            firstName: "Clase",
            lastName: "Boson",
            personNumber: 195304251985
        }
    }
    ]
}

我得到的ERROR是“TypeError: Cannot read property '0' of undefined”

  61 |         <Row>
> 62 |         <Col>{this.state.housingData ? <h1>{this.state.housingData.buildings[0].name}</h1> : ''}</Col>
  63 |    </Row>
  64 |     </Row>
  65 | );

如果我改变:

<Row>
<Col>
{this.state.housingData ? <h1>{this.state.housingData.buildings[0].name}</h1> : ''}
</Col>
</Row>

收件人:

<Row>
<Col>
{this.state.housingData ? <h1>{JSON.stringify(this.state.housingData.buildings)}</h1> : ''}</Col>
</Row>

对象打印如下:

[{"name":"something1","id":1,"members":{"id":1,"firstName":"Hans","lastName":"Ottoson","personNumber":198703259715}},{"name":"something2","i":2,"members":{"id":1,"firstName":"Clase","lastName":"Boson","personNumber":195304251985}}]

【问题讨论】:

    标签: arrays reactjs object


    【解决方案1】:

    您的组件第一次渲染时,this.state.housingData 是一个空对象,所以this.state.housingData[0] 确实是undefined

    如果我将 [...] 更改为 [...] 对象会像这样打印 [...]

    您看到的是组件的 second 渲染的输出。这“有效”是因为代码更改不会在组件的第一次渲染中导致错误。


    这是您的问题的简化示例:

    var housingData = {};
    
    housingData ? housingData[0].foo : null

    一种可能的解决方案是改善您的状况。不要仅仅检查this.state.housingData 是否真实,而是确保它实际上包含元素(this.state.housingData.length &gt; 0)。

    此外,将其初始化为数组也可能更有意义。

    var housingData = [];
    
    housingData.length > 0 ? housingData[0].foo : null

    【讨论】:

    • 感谢一百万,我因为这个而秃顶了......真实和虚假已经让我出局的次数超出了应有的次数。需要更多地了解它!是的,将 HousingData 初始化为数组更有意义!再次感谢!
    • @Felix 你好先生,你能帮我stackoverflow.com/questions/67498940/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2016-10-18
    相关资源
    最近更新 更多