1、安装 pubsub-js
npm install pubsub-js
2、消息发布
PubSub.publish('update-list',{isLoding:false,users:res.data.items});
3、消息订阅
```javascript
componentDidMount() {
//订阅消息
PubSub.subscribe('update-list',(msg,keyword)=>{
this.setState(keyword)
})
4、完整代码
App.js
```javascript
//创建“外壳”组件APP
import React, {Component} from "react";
//引入Search组件
import Search from "./components/Search";
//引入List组件
import List from "./components/List";
//创建并暴露App组件
export default class App extends Component {
render() {
return (
<div className="container">
<Search ></Search>
<List></List>
</div>
)
}
}
List组件
import React, {Component} from "react";
import PubSub from 'pubsub-js'
//引入样式
import "./index.css";
export default class List extends Component {
state={
users:[],
isFirst:true,//是否第一次加载数据
isLoding:false,//是否正在加载数据
err:''//是否加载失败
}
componentDidMount() {
//订阅消息
PubSub.subscribe('update-list',(msg,keyword)=>{
this.setState(keyword)
})
}
render() {
const {users,isFirst,isLoding,err}=this.state
return(
<div className="row">
{
isFirst?<h2>欢迎使用,输入关键字,随后点击搜素</h2>:
isLoding?<h2>正在加载中...</h2>:
err?<h2 style={{color:'red'}}>{err}</h2>:
users.map((userObj)=>{
return(
<div key={userObj.id} className="card">
<a href={userObj.html_url} target="_blank" rel="noreferrer">
<img alt={"reactjs"} src={userObj.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
);
}
}
样式
.album {
min-height: 50rem; /* Can be removed; just added for demo purposes */
padding-top: 3rem;
padding-bottom: 3rem;
background-color: #f7f7f7;
}
.card {
float: left;
width: 33.333%;
padding: .75rem;
margin-bottom: 2rem;
border: 1px solid #efefef;
text-align: center;
}
.card > img {
margin-bottom: .75rem;
border-radius: 100px;
}
.card-text {
font-size: 85%;
}
search组件
import React, {Component} from "react";
import PubSub from 'pubsub-js'
//引入axios
import axios from 'axios';
export default class Search extends Component {
search = () =>{
//获取用户的输入(连续解构赋值+重命名)
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});
}
)
}
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>
);
}
}