一.效果图
二.开始布局
-
import React, { Component } from 'react'
import './App.scss'
import Search from './components/Search/index'
import List from './components/List/index'
export default class App extends Component {
state = {//初始化界面
users: [],//users初始值为数组
isFirst: true,//是否为第一次打开界面
isLoading: false,//标识是否处于加载中
err: '' //存储请求相关错误信息
}
updateAppState = (stateObj) => {
this.setState(stateObj)
}
render() {
const { users } = this.state
return (
<div className="container">
<Search updateAppState={this.updateAppState} />
<List {...this.state} />
</div>
)
}
}
-
import axios from 'axios';
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class Search extends Component {
search = () => {
//获取用户的输入
const { value } = this.keyWordElement
//发送请求前通知List更新状态
this.props.updateAppState({ isFirst: false, isLoading: true })
// //发送网络请求
axios.get(`/api1/search/users?q=${value}`).then(
response => {
// 请求成功后通知List更新状态
this.props.updateAppState({ isLoading: false, users: response.data.items })
},
error => {
// 请求失败后通知List更新状态
PubSub.publish('atguigu', { isLoading: false, err: error.message })
}
)
}
render() {
return (
<div>
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
<input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />
<button onClick={this.search}>Search</button>
</div>
</section>
</div >
)
}
}
-
import React, { Component } from 'react'
export default class List extends Component {
render() {
const { users, isFirst, isLoading, err } = this.props
return (
<div className="row">
{
isFirst ? <h2>欢迎使用,输入关键字,随后点击搜索</h2> :
isLoading ? <h2>Loading…………</h2> :
err ? <h2 style={{ color: 'red' }}>{err}</h2> :
users.map((userObj) => {
return (
<div key={userObj.id} className="card">
<a rel="noreferrer" href={userObj.html_url} target="_blank">
<img alt="head_portrait" src={userObj.avatar_url} style={{ width: '100px' }} />
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
)
}
}