反应其他国家-添加有关国家的信息

时间:2018-07-13 07:07:55

标签: javascript reactjs api

我不知道如何添加有关国家的信息。如果在渲染函数中添加<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

1 个答案:

答案 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>