React & Fetch
安装命令 npm install isomorphic-fetch --save
import React from 'react'
import fetch from 'isomorphic-fetch'
class CountryList extends React.Component {
constructor(props) {
super(props);
this.state = {
countryNames: [],
loading: false,
err: false
}
}
componentDidMount() {
this.setState({loading: true});
fetch('https://restcountries.eu/rest/v1/all111')
.then(response => response.json())
.then(json => json.map(country => country.name))
.then(countryNames => this.setState({countryNames, loading: false}))
.catch(err => this.setState({loading: false, err: true}));
}
render() {
const {countryNames, loading, err} = this.state;
return (loading) ?
<div>loading country names...</div> :
(err) ?
<p>loading fail...</p> :
<ul>
{
countryNames.map(
(x, i) => <li key={i}>{x}</li>
)
}
</ul>
}
}
export default CountryList