1、代码
import React, {Component} from "react";
import PubSub from 'pubsub-js'
//引入axios
export default class Search extends Component {
search = async () => {
//获取用户的输入(连续解构赋值+重命名)
const {keyword: {value: keyword}} = this;
//发送请求前通知List组件更新状态
/*this.props.updateAppState({isFirst:false,isLoding: true});*/
PubSub.publish('update-list', {isFirst: false, isLoding: true});
//发送网络请求 https://api.github.com/search/users?q=xxxxxx
// axios.get(`https://api.github.com/search/users?q=${keyword}`).then(
// res=>{
// //请求成功后通知List组件更新状态
// // const {items} = res.data;
// // this.props.updateAppState({isLoding:false,users:items});
// // console.log(items)
// PubSub.publish('update-list',{isLoding:false,users:res.data.items});
// },
// err=>{
// //请求失败通知App组件更新状态
// // this.props.updateAppState({isLoding:false,err:err.message});
// PubSub.publish('update-list',{isLoding:false,err:err.message});
// }
// )
//使用fetch发送网络请求 (未优化)
// fetch(`https://api.github.com/search/users?q=${keyword}`).then(
// res=>{
// console.log('请求成功了')
// return res.json();
// },
// // err=>{
// // console.log('请求失败了')
// // return new Promise(()=>{})
// // }
// ).then(
// res=>{
// console.log('获取数据成功了',res)
// },
// // err=>{console.log('获取数据失败了',err)}
// ).catch((err)=>{console.log('请求失败了',err)})
//使用fetch发送网络请求 (优化)
try {
const response = await fetch(`https://api.github.com/search/users?q=${keyword}`)
const data = await response.json();
console.log('获取数据成功了', data)
PubSub.publish('update-list',{isLoding:false,users:data.items});
}catch (e) {
console.log('获取数据失败了',e)
PubSub.publish('update-list',{isLoding:false,err:e.message});
}
}
render()
{
return(
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
<input ref={c=>this.keyword=c} type="text" placeholder="enter the name you search"/>
<button onClick={this.search}>Search</button>
</div>
</section>
);
}
}