这是我的第一个React项目,但我遇到了这个问题:“ ./ src / pages / EventsPage.jsx第64行:'events'未定义为no-undef”。 第64行是{events}。变量事件在第33行声明。但是为什么我不理解'events'的定义。
这是主要的反应成分。
import React, { Component } from "react";
import Events from "./../components/Events";
export default class EventsPage extends Component {
constructor(props) {
super(props);
this.state = {
eventData: {},
isLoggedin: true
};
}
componentDidMount() {
fetch("http://localhost:5999/events/" + this.props.match.params.userId, {
headers: {
"Content-Type": "application/json"
},
method: "GET",
mode: "cors",
credentials: "include"
})
.then(response => response.json())
.then(data => {
if (data["code"] === 200) {
console.log("OK");
this.setState({
eventData: data.events_data,
isLoggedin: true
});
let events = this.state.eventData.map(event => (
<Events
name={event.name}
image_url={event.image_url}
start_time={event.start_time}
end_time={event.end_time}
price={event.price}
age_from={event.age_from}
age_to={event.age_to}
x_coord={event.x_coord}
y_coord={event.y_coord}
status={event.status}
status_id={event.status_id}
members_total={event.members_total}
members_needed={event.members_needed}
owner_id={event.owner_id}
address={event.address}
/>
));
} else {
console.log("NOT OK");
this.setState({
eventData: data.events_data,
isLoggedin: false
});
}
});
}
render() {
return { events };
}
}
答案 0 :(得分:1)
您不能在events
方法中创建componentDidMount
变量,而不能在render
方法中访问它。您可以直接在render方法中创建events
变量,因为它会在您完成fetch
请求并更新状态后重新运行。
还要确保在初始状态下将eventData
设置为一个空数组而不是一个空对象,否则尝试在其上使用map
方法时会出错。
export default class EventsPage extends Component {
constructor(props) {
super(props);
this.state = {
eventData: [],
isLoggedin: true
};
}
componentDidMount() {
fetch("http://localhost:5999/events/" + this.props.match.params.userId, {
headers: {
"Content-Type": "application/json"
},
method: "GET",
mode: "cors",
credentials: "include"
})
.then(response => response.json())
.then(data => {
if (data["code"] === 200) {
console.log("OK");
this.setState({
eventData: data.events_data,
isLoggedin: true
});
} else {
console.log("NOT OK");
this.setState({
eventData: data.events_data,
isLoggedin: false
});
}
});
}
render() {
let events = this.state.eventData.map(event => (
<Events
name={event.name}
image_url={event.image_url}
start_time={event.start_time}
end_time={event.end_time}
price={event.price}
age_from={event.age_from}
age_to={event.age_to}
x_coord={event.x_coord}
y_coord={event.y_coord}
status={event.status}
status_id={event.status_id}
members_total={event.members_total}
members_needed={event.members_needed}
owner_id={event.owner_id}
address={event.address}
/>
));
return <>{events}</>;
}
}