代码变更涉及的文件有:
- App.js,即App组件。
- components/Search/index.jsx,即Search组件。
- components/List/index.jsx,即List组件。
App.js(App组件)
import React, { Component } from 'react'
import Search from "./components/Search";
import List from "./components/List";
export default class App extends Component {
state = {
users:[],
isFirst:true,
isLoading:false,
errorMsg:""
}
changeState = (stateObj) => {
this.setState(stateObj);
}
render() {
const {changeState} = this;
return (
<div className="container">
<Search changeState={changeState}/>
<List {...this.state}/>
</div>
)
}
}
Search/index.jsx(Search组件)
import React, { Component } from 'react';
import axios from "axios";
export default class index extends Component {
handleClick = () => {
const {keywordEle:{value:keyword}} = this;
const {changeState} = this.props;
changeState(({isFirst:false,isLoading:true}))
axios.get(`https://api.github.com/search/users?q=${keyword}`).then(
response => {
console.log("请求成功了",response.data);
changeState({isLoading:false,users:response.data.items})
},
error => {
changeState({isLoading:false,errorMsg:error.message})
}
)
}
render() {
const {handleClick} = this;
return (
<section className="jumbotron">
<h3 className="jumbotron-heading">搜索Github用户</h3>
<div>
<input ref={c => this.keywordEle = c} type="text" placeholder="输入关键词"/>
<button onClick={handleClick}>搜索</button>
</div>
</section>
)
}
}
List/index.jsx(List组件)
import React, { Component } from 'react'
import "./index.css";
export default class index extends Component {
render() {
const { isFirst,isLoading,users,errorMsg } = this.props;
return (
<div className="row">
{ isFirst ? <h2>欢迎使用,输入关键词,点击按钮即可搜索</h2> :
isLoading ? <h2>正在加载...</h2> :
errorMsg ? <h2 style={{color:'red'}}>{errorMsg}</h2> :
users.map(userObj => {
return (
<div className="card" key={userObj.id}>
<a href={userObj.html_url} target="_blank" rel="noreferrer">
<img alt="avatar" src={userObj.avatar_url} style={{ width: '100px' }} />
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
)
}
}