访问对象属性时出现未定义的TypeError

时间:2019-09-26 23:26:20

标签: javascript reactjs

我有一个数组,可在控制台中输出:

HOUSES (11) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

我只需要第一个对象值。因此,当我控制台第一个这样的元素时:

console.log("SINGLE HOUSE", houses[0])

您将看到第一个元素:

SINGLE HOUSE 
{id: 1, count: 0, name: "House1", image: "https://cdn0.iconfinder.com/data/icons/free-business-desktop-icons/256/Home.png"}
count: 0
id: 1
image: "https://cdn0.iconfinder.com/data/icons/free-business-desktop-icons/256/Home.png"
name: "House1"
__proto__: Object

但是当我尝试访问第一个对象的name属性时,像这样:

console.log("SINGLE HOUSE", houses[0].name)

我遇到一个错误,它说“名称”未定义:

TypeError: Cannot read property 'name' of undefined

这是我的组件的外观:

import React, { useContext, useEffect, useState } from "react";
import { connect } from "react-redux";
import Image from "../../components/Image/Image";
import Title from "../../components/Title/Title";
import Counter from "../../components/Counter/Counter";
import Button from "../../components/Button/Button";

import {Single} from "./HouseSingle.styled";
import { getSingleHouseAPI } from "../../services/api";
import { getHousesAPI } from "../../services/api";
import { getHouses, getSingleHouse } from '../../state/house/actions';


const HouseSingle = (props) => {

     const { house, houses } = props

     const { image, name, id, count} = house;
     //  const { image, name, id, count} = houses[0];


    const handleIncrement = (data) => {
     console.log('increment')
    }

    const handleDecrement = (data) => {
     console.log('decrement')
     }


      console.log("SINGLE HOUSE", houses[0])
    return ( 

        <Single>
        <div className="house">
         <Image src={image} />  
          <Title title={name} />

          <Counter count={count} />

          <Button type="Increment" onClick={handleIncrement}/>
          <Button type="Decrement" onClick={handleDecrement} />

        </div>
        </Single>
     );
}


const matStateToProps = state => {
     const { house: { singleHouse: { data: house } }} = state;
     const { house: { allHouses: {data: houses}}} = state;
     return {
          house,
          houses
     }
}
export default connect(matStateToProps)(HouseSingle);

1 个答案:

答案 0 :(得分:0)

如果您使用console.log,则可能是您尝试访问的属性可能还不存在。

尝试一下。

setTimeout(function()
{
    var houseName = houses[0].name ;  
}, 
100);