试图将数据从API调用传递到组件,但是API调用后数据不确定。我在React上很新,因此,任何帮助都将不胜感激!所有类都在下面,我没有包含形式的组合,但它可以使数据恰好
获得。app.js
import React, { Component } from "react";
import axios from "axios";
import ShowtimeList from "./components/ShowtimeList";
import Form from "./components/Form";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
isFetching: true
};
this.getShowtimes = this.getShowtimes.bind(this);
}
getShowtimes(event) {
event.preventDefault();
const startDate = event.target.startDate.value;
const numDays = event.target.numDays.value;
const zipCode = event.target.zipCode.value;
const radius = event.target.radius.value;
const unit = event.target.units.value;
let showtimes = {};
const API_KEY = "<API-KEY>";
const call =
"http://data.tmsapi.com/v1.1/movies/showings?startDate=" +
startDate +
"&numDays=" +
numDays +
"&zip=" +
zipCode +
"&radius=" +
radius +
"&units=" +
unit +
"&api_key=" +
API_KEY;
this.setState({ isFetching: !this.state.isFetching });
axios
.get(call)
.then(function(response) {
console.log(response.data);
showtimes = response.data;
console.log(showtimes);
})
.catch(function(error) {
console.log(error);
});
}
renderShowtimes(showtimes) {
let times = "";
console.log(this.showtimes); ----- Undefined
if (this.showtimes != null) {
times = <ShowtimeList showtimes={this.showtimes} />;
} else {
times = "No Showtimes In Your Area";
}
return times;
}
render() {
return (
<div>
{this.state.isFetching ? (
<Form getShowtimes={this.getShowtimes} />
) : (
this.renderShowtimes()
)}
</div>
);
}
}
export default App;
showtimelist.js
import React, { Component } from "react";
import Showtime from "./Showtime";
class ShowtimeList extends Component {
render() {
return (
<ul>
{this.props.showtimes.map(showtime => {
return <Showtime showtime={showtime} />;
})}
</ul>
);
}
}
export default ShowtimeList;
showtime.js
import React, { Component } from "react";
class Showtime extends Component {
render() {
return <li>{this.props.showtime}</li>;
}
}
export default Showtime;
使用 state
存储展示时间并将其作为道具传递。在您的state
内,添加放映时间。然后在您的axios
呼叫中而不是showtimes = response.data;
内,请执行setState
。this.setState({showtimes: response.data})
然后做<ShowtimeList showtimes={this.state.showtimes} />
您没有在组件范围内声明变量放映时
无论如何,我建议将这些数据存储在您的组件状态中。
在rendershowtime中,您要提出一个放映的参数
您永远不会将showtimes
设置为状态。要解决这个问题:
...
var _this = this;
axios
.get(call)
.then(function(response) {
console.log(response.data);
showtimes = response.data;
_this.setState({ showtimes: showtimes });
console.log(showtimes);
})
.catch(function(error) {
console.log(error);
});
...