为什么定义了却出现“TypeError:无法读取未定义的属性‘airline’”?
我尝试访问数据数组的嵌套对象。它正在运行,突然间,它开始返回 “TypeError:无法读取未定义的属性‘airline’” 。我检查了一下,似乎找不到我触摸过的任何内容。
我有这些数据,当我尝试访问
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: Cannot read property 'airline' of undefined DestinationProvider.getFlights src/context.js:52 > 52 | console.log(tempFlights[0].airline); | ^ 53 | 54 | const flights = tempFlights.filter(flight => 55 | View compiled Flights.render src/pages/Flights.js:24 21 | const { getFlights } = this.context 22 | const slug = Object.fromEntries(new URLSearchParams(this.state.slug)) 23 | const { to, from, departureDate } = slug > 24 | const flights = getFlights(to, from, departureDate)
事实上,我仍然不知道为什么我无法从函数内部访问这些对象,但我终于弄清楚了为什么我的过滤函数突然开始返回一个空数组。
我试图在过滤函数中比较这三个值,
const flights = tempFlights.filter(flight =>
flight.from.destination.toLowerCase() === from.toLowerCase() &&
flight.to.destination.toLowerCase() === to.toLowerCase() &&
flight.departureDate >= departureDate
);
但最后一次比较是错误的。我应该比较
flight.departureDate <= divineDate.toString()
而不是
flight.departureDate >= divineDate
您获取到​​
tempFlights[0] is undefined
是因为在您尝试访问(或记录)它时,它是未定义的(
this.state.destinations
是
[]
- 初始状态)。
但请注意,一段时间后,即
componentDidMount
已执行并且
setState
已被调用时,它会被
defined
。
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,
}
}