代码如下:
App.js
import React, { Component } from 'react'
import {Search,List} from './components';
export default class App extends Component {
//初始化状态
state={
users:[],//users初始值为数组
isFirst:true,//是否为第一次打开页面
isLoading:false,//标识是否处于加载中
err:'',//存储请求相关的错误信息
}
//更新app的state
updateAppState = (stateObj)=>{
this.setState(stateObj)
}
// saveUsers = (users)=>{
// this.setState({users})
// }
render() {
return (
<div className="container">
<Search updateAppState={this.updateAppState}></Search>
<List {...this.state}></List>
</div>
)
}
}
Search.js
import React, { Component } from 'react'
import axios from 'axios'
export default class Search extends Component {
search=()=>{
//获取当前用户输入
// //常规的解构赋值
// const {value} = this.inputt 也就的等于=== const {inputt:{value}} = this
// console.log(value);
//连续的解构赋值+重命名
const {inputt:{value:valuelue}} = this
console.log(valuelue);
//发送请求之前通知app更新状态
this.props.updateAppState({isFirst:false,isLoading:true})
//发送网络请求
axios.get(`http://localhost:3000/api2/search/users?q=${valuelue}`).then(
response =>{
console.log('请求成功了',response.data);
//请求成功通知app更新状态
this.props.updateAppState({isLoading:false,users:response.data.items})
},
error =>{console.log('请求失败了',error);
//请求失败通知app更新状态
this.props.updateAppState({isLoading:false,err:error.message})
}
)
}
render() {
return (
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
<input ref={c=>this.inputt=c} type="text" placeholder="enter the name you search"/>
<button onClick={this.search}>搜索</button>
</div>
</section>
)
}
}
List.js
import React, { Component } from 'react'
import './index.css'
export default class List extends Component {
render() {
const {users,isFirst,isLoading,err}=this.props
return (
<div className="row">
{
isFirst ? <h2>欢迎使用,请输入关键字,点击搜索即可查看搜索结果</h2> :
isLoading ? <h2>加载中....</h2> :
err ? <h2 style={{color:'red'}}>{err}</h2> :
users.map((item)=>{
console.log('aaa');
return(
<div className="card" key={item.id}>
<a rel="noreferrer" href={item.html_url} target="_blank">
<img alt="头像" src={item.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{item.login}</p>
</div>
)
})
}
</div>
)
}
}
setupProxy.js proxy解决跨域专用文件名 js能够识别
const proxy = require('http-proxy-middleware')
module.exports = function(app){
app.use(
proxy('/api1',{ //遇见/api1前缀的请求,就会触发该代理配置
target:'http://www.kuwo.cn', //请求转发给谁
changeOrigin:true,//控制服务器收到的请求头中Host的值
pathRewrite:{'^/api1':''} //重写请求路径(必须)
}),
proxy('/api2',{
target:'http://localhost:5000',
changeOrigin:true,
pathRewrite:{'^/api2':''}
}),
)
}
通过PubSub订阅发布 实现两个组件间传值 不使用App 而是将数据直接存在list中 在list中订阅,search中将数据发布给list
总结