尝试将数据从api调用传递给组件,但在api调用之后,数据变得不确定。我相当新的反应所以任何帮助将不胜感激谢谢!所有的类都在下面,我没有包含表单componentsnet但它获得的数据很好
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;
答案 0 :(得分:0)
您没有在组件范围内声明变量放映时间,这就是为什么this.showtimes将始终未定义的原因。
无论如何,我建议将这些数据存储在组件状态中。
同样在renderShowtimes中你要求一个showtime参数,你在稍后调用render方法中的函数时不会传递它。
答案 1 :(得分:0)
您永远不会将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);
});
...
答案 2 :(得分:0)
使用state
存储放映时间并将其作为道具传递下去。在state
内,添加放映时间。然后在axios
来电而非showtimes = response.data;
内,执行setState
。 this.setState({showtimes: response.data})
然后执行<ShowtimeList showtimes={this.state.showtimes} />