我不知道如何添加有关国家的信息。如果在渲染函数中添加<li>{response}</li>
,它将显示所有信息,但是如果我执行<li>{response.name}</li>
,则不会显示任何信息。任何想法如何解决?我会很感激帮助
import React from "react";
class App extends React.Component {
constructor() {
super();
this.state = {
searchText: "",
country: []
};
}
onChangeHandle(event) {
this.setState({ searchText: event.target.value });
}
onSubmit(event) {
event.preventDefault();
const { searchText } = this.state;
$.get(`https://restcountries.eu/rest/v1/name/${searchText}`).success(
function(response) {
this.setState({ country: response });
}.bind(this)
);
}
render() {
let response = JSON.stringify(this.state.country);
return (
<main>
<section class="search">
<form onSubmit={event => this.onSubmit(event)}>
<h2>Country search engine</h2>
<input
id="country-name"
placeholder="e.g. Poland"
type="text"
onChange={event => this.onChangeHandle(event)}
value={this.state.searchText}
/>
</form>
</section>
<section class="results">
<div class="country-info">
<ul id="countries">
<li>{response.name}</li>
</ul>
</div>
</section>
<footer>
<p>Michał Plebański</p>
</footer>
</main>
);
}
}
export default App; here
答案 0 :(得分:0)
https://restcountries.eu/rest/v1/name/{countryName}
将返回Array
的结果。因此,您应该使用Array.map
来渲染对象:
<section class="results">
<div class="country-info">
<ul id="countries">
{this.state.country.map(country => <li>{country .name}</li>)}
</ul>
</div>
</section>