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

})

});

以上是 React App:如何使用抓取显示来自api的数据 的全部内容, 来源链接: utcz.com/qa/257094.html

回到顶部