es2015版本:
//需要 jquery库
class MyList extends React.Component {
constructor(...args) {
super(...args);
this.state = {
loading: true,
error: null,
data: null
};
}
componentDidMount() {
const url = 'https://api.github.com/search/repositories?q=javascript&sort=stars';
$.getJSON(url)
.done(
(value) => this.setState({
loading: false,
data: value
})
).fail(
(jqXHR, textStatus) => this.setState({
loading: false,
error: jqXHR.status
})
);
}
render() {
if (this.state.loading) {
return <span>Loading...</span>;
}
else if (this.state.error !== null) {
return <span>Error: {this.state.error}</span>;
}
else {
/* 你的代码填入这里 */
// console.log(this.state.data);
let projects = this.state.data.items,
result = [];
projects.forEach(p => {
let item = <li>{p.id}:{p.name}</li>;
result.push(item);
});
return (
<div>
<p>API 数据获取成功</p>
<p><ul>
{result}
</ul></p>
</div>
);
}
}
};
ReactDOM.render(
<MyList/>,
document.getElementById('example')
);