【问题标题】:Why "TypeError: Cannot read property 'airline' of undefined" when it is defined?为什么在定义时出现“TypeError:无法读取未定义的属性'航空公司'”?
【发布时间】:2020-09-04 22:39:46
【问题描述】:

我正在尝试访问我的数据数组的嵌套对象。它正在工作,突然间,它开始返回 “TypeError: Cannot read property 'airline' of undefined”。我检查了,我似乎在任何地方都找不到我触摸过的任何东西。

我有这个数据,当我尝试访问console.log(tempflights[0]) 时,返回数据,但是当我访问console.log(tempFlights[0].airline) 或数组中的任何其他对象属性时,它返回一个类型错误

我也在尝试将存储的数据与接收到的数据进行比较,看看是否匹配。

谁能帮我弄清楚我哪里弄错了。 注意:我对 React 和 Js 很陌生。

import logo1 from "./images/delta.png";
import img1 from "./images/w1.jpg";


export default [
  {
    sys: {
      id: "1"
    },
    fields: {
      from: {
        destination: "London",
        slug: "LHR",
      },
      to: {
        destination: "New York",
        slug: "LGA",
      },
      airline: {
        name: "Delta",
        airlineId: "DL 214",
        logo:
        {
          fields: {
            file: {
              url: logo1
            }
          }
        }

      },
      tripClass: "economy",
      direct: true,
      stopOver: {
        destination: "",
        slug: ""
      },
      minPrice: 900,
      departureDate: "2020-06-05",
      roundTrip: true,
      returnDate: "2020-07-05",
      luggageLimit: 50,
      totalDuration: "6h 30m",
      featured: true,
      images: [
        {
          fields: {
            file: {
              url: img1
            }
          }
        }
      ]
    }
  },
]


import React, { Component, createContext } from 'react'
import items from './data'



const DestinationContext = createContext();
// create context Provider

class DestinationProvider extends Component {
    //set up state
    state = {
        destinations: [],
        sortedDestinations: [],
        featuredDestinations: [],
        loading: true,
    }
 
    componentDidMount() {
        let destinations = this.formatData(items)
        let featuredDestinations = destinations.filter(destination =>
            destination.featured === true);

        this.setState({
            destinations,
            featuredDestinations,
            sortedDestinations: destinations,
            loading: false
        })
    }

    formatData(items) {
        let tempItems = items.map(item => {
            let id = item.sys.id
            let images = item.fields.images.map(image => image.fields.file.url);

            let destination = { ...item.fields, images, id }
            return destination;
        })
        return tempItems;
    }

    getFlights = (to, from, departureDate) => {
        let tempFlights = [...this.state.destinations];
        console.log(tempFlights[0].airline);

        const flight = tempFlights.filter(flight =>

            flight.to.destination.toLowerCase() === to.toLowerCase() &&
            flight.from.destination.toLowerCase() === from.toLowerCase() &&
            flight.departureDate >= departureDate
        );
        return flight;
    }
    render() {
        return (
            <DestinationContext.Provider value={{
                ...this.state,
                getFlights: this.getFlights
            }}>
                {this.props.children}
            </DestinationContext.Provider>
        );
    }
}
const DestinationConsumer = DestinationContext.Consumer;

export { DestinationProvider, DestinationConsumer, DestinationContext };

错误:

TypeError:无法读取未定义的属性“航空公司” DestinationProvider.getFlights src/context.js:52 > 52 | console.log(tempFlights[0].airline); | ^ 53 | 54 |常量航班 = tempFlights.filter(flight => 55 | 查看编译的 Flights.render src/pages/Flights.js:24 21 |常量 { getFlights } = this.context 22 | const slug = Object.fromEntries(new URLSearchParams(this.state.slug)) 23 | const { to, from, leaveDate } = slug > 24 |常量航班 = getFlights(to, from, leaveDate)

【问题讨论】:

  • 看一眼,不就是tempflights.fields.airline吗?
  • @Redline 感谢您的快速回复。如您所见,该行中的数据被展平:let destination = { ...item.fields, images, id },因此在访问时绕过了这些字段。
  • console.log(tempflights[0])console.log(tempFlights[0].airline)。调试时注意tempflights上的大小写。 tempFlightstempflights 是不同的变量。也就是说......代码块看起来很合理,并且在我不计后果的快速阅读中始终使用tempFlights
  • @HPierce 我相信错误是在输入问题时,而不是在代码中
  • plz,你能告诉我错误信息吗?

标签: javascript json reactjs object nested


【解决方案1】:

我仍然不知道为什么我不能从函数中访问这些对象,但我终于弄清楚了为什么我的过滤器函数突然开始返回一个空数组。

我试图在过滤函数中比较这三个值,

 const flights = tempFlights.filter(flight =>
            flight.from.destination.toLowerCase() === from.toLowerCase() &&
            flight.to.destination.toLowerCase() === to.toLowerCase() &&
            flight.departureDate >= departureDate
        );

但最后的比较是错误的。我应该比较 flight.departureDate &lt;= departureDate.toString() 不是 flight.departureDate &gt;= departureDate

【讨论】:

    【解决方案2】:

    您得到tempFlights[0] is undefined,因为在您尝试访问(或记录)它时它是未定义的(this.state.destinations[] - 初始状态)。

    但请注意,它会在一段时间后定义,即当componentDidMount 已执行并且setState 已被调用时。

      getFlights = (to, from, departureDate) => {
        let tempFlights = [...this.state.destinations]
        console.log(tempFlights[0].airline) // Error: tempFlights[0] is undefined
    
        const flight = tempFlights.filter(
          (flight) =>
            flight.to.destination.toLowerCase() === to.toLowerCase() &&
            flight.from.destination.toLowerCase() === from.toLowerCase() &&
            flight.departureDate >= departureDate
        )
        return flight
      }
    

    如果你像这样在构造函数中初始化你的状态,你不应该在getFlights 中看到Error: tempFlights[0] is undefined。但我认为您不能这样做,因为 items 并不是您在本示例中提供的真正的固定/硬编码值。但是我认为您的状态将设置为componentDidMount,并且更改将正确传播,因此如果您只是删除getFlight 中的控制台日志,则应该不会再出现错误,因为那时它确实在尝试从未定义中读取。

      constructor(props) {
        super(props)
        let destinations = this.formatData(items)
        let featuredDestinations = destinations.filter(
          (destination) => destination.featured === true
        )
        this.state = {
          destinations,
          featuredDestinations,
          sortedDestinations: destinations,
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 1970-01-01
      • 2021-07-02
      • 2021-11-13
      • 2020-02-04
      • 2020-11-29
      • 1970-01-01
      相关资源
      最近更新 更多