我正在尝试使用React从外部api显示学校数据。我只想尝试显示学校名称。学校名称出现在控制台中,但它不会显示在浏览器中.api调用是正确的,因为它在Postman中有效。这是我的代码:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
schoolName: '',
// schoolData: {}
}
}
fetchSchool(event) {
event.preventDefault();
const apiKey = 'XdOHSc8fKhMKidPu2HWqCZmMy9OxtCJamGC580Bi';
const fields = `_fields=school.name,2015.aid.median_debt.completers.overall,2015.cost.tuition.in_state&school.name=${this.state.schoolName}`;
const requestUrl = `https://api.data.gov/ed/collegescorecard/v1/schools?&api_key=${apiKey}&${fields}`;
const school = fetch(requestUrl).then((res) => res.json()).then((data) => console.log(data.results[0]['school.name']));
this.setState({
schoolName: school
// schoolData: school
})
console.log(this.state.schoolName);
}
setSchool(event) {
event.preventDefault();
this.setState({
schoolName: event.target.value
});
}
render() {
// const schoolname = this.state.schoolName[0];
// const {schooName} = this.state;
return (
<div>
<form action="/school" method="GET" id="myform">
<input type="text" className="form-control" id="enter_text" onChange={this.setSchool.bind(this)} />
<button onClick={this.fetchSchool.bind(this)} type="submit" className="btn btn-primary" id="text-enter-button button submit">Submit</button>
</form>
<div>
<p>School: {this.state.school} </p>
</div>
</div>
);
}
}
export default App;
答案 0 :(得分:1)
fetch
是异步的。因此,在获取数据之前调用setState
。
要解决此问题,请从this.setState
功能
then
const school = fetch(requestUrl)
.then((res) => res.json())
.then((data) => {
console.log(data.results[0]['school.name'])
this.setState({
schoolName: data.results[0]['school.name'],
schoolData: data.results
})
});
答案 1 :(得分:0)
在渲染方法中更改此行,因为schoolName
是您的状态变量,而不是school
。
<p>School: {this.state.school} </p>
到
<p>School: {this.state.schoolName} </p>