React App:如何使用抓取显示来自api的数据
我想使用React从外部API显示学校数据。我只是想显示一个学校名称开始。学校名称出现在控制台中,但不会显示在浏览器中.API调用是正确的,因为它在Postman中运行。这里是我的代码:React App:如何使用抓取显示来自api的数据
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;
在渲染处理方法改变这一行,因为schoolName
是你的状态变量,而不是school
。
<p>School: {this.state.school} </p>
到
<p>School: {this.state.schoolName} </p>
fetch
是异步的。因此,在获取数据之前调用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
})
});
谢谢!这工作...差不多。学校名称显示在浏览器中,但显示为我输入,而不是在点击“提交”之后。 – user8767190
从'input'元素中删除'onChange = {this.setSchool.bind(this)}' –
这给了我一个新的错误:无法读取未定义的'school.name'的属性(在获取请求中) – user8767190
我建议删除值apiKey如果是敏感的信息,请拨打
this.setState
。 – Kunukn