将上一章的github搜索案例改造成行兄弟间通信
PubSub.publish("state",{keyword:keyword});
componentDidMount() {
//有的参数不用又不能不写,下划线占位
this.token=PubSub.subscribe("state",(_,data)=>{
this.setState(data)
})
}
//一定要记得取消订阅
componentWillUnmount() {
PubSub.unsubscribe( this.token);
}
发布
class Search extends Component {
search = () => {
//连续解构赋值 + 重命名
const {keySearch: {value: keyword}} = this;
PubSub.publish("state",{loading:true});
axios.get(`https://api.github.com/search/users?q=${keyword}`).then(({data}) => {
PubSub.publish("state",{userInfo:data.items,loading:false})
}).catch(error => {
PubSub.publish("state",{loading:false,err:error})
})
};
render() {
return (
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div className="input-group">
<input type="text" ref={c => this.keySearch = c} className="form-control"
placeholder="enter the name you search"/>
<div className="input-group-btn">
<button type="button" className="btn btn-danger" onClick={this.search}>Search</button>
</div>
</div>
</section>
);
}
}
export default Search;
接受
class UserList extends Component {
state = {
userInfo: [],
loading: false,
err: ""
};
componentDidMount() {
//有的参数不用又不能不写,下划线占位
this.token = PubSub.subscribe("state", (_, data) => {
this.setState(data)
})
}
componentWillUnmount() {
PubSub.unsubscribe(this.token);
}
render() {
const {userInfo: items, loading} = this.state;
return (
<div className="row">
{loading ? <div>loading</div> : items.length === 0 ? <div>hello</div> : items.map(item => {
return (
<div className="card" key={item.id}>
<a href={item.html_url} target="_blank" rel="noreferrer">
<img alt="avatar" src={item.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{item.login}</p>
</div>
)
})}
</div>
);
}
}
export default UserList;