消息订阅与发布技术
安装第三方库
npm install pubsub-js
使用时导入库
import PubSub from 'pubsub-js';
例子:
订阅
import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import './index.css'
export default class List extends Component {
state = {//初始化状态
users:[],//users初始值为数组
isFirst:true,//是否为第一次打开页面
isLoading:false,//标识是否处于加载中
err:'',//存储请求相关的错误信息
}
componentDidMount(){
this.token = PubSub.subscribe('atguigu',(_,stateObj)=>{
this.setState(stateObj)
})
}
componentWillUnmount(){
PubSub.unsubscribe(this.token)
}
render() {
const {users,isFirst,isLoading,err} = this.state
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 href={userObj.html_url} rel="noreferrer">
<img alt='head_portrait' src={userObj.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
);
}
}
发布
import axios from 'axios'; import PubSub from 'pubsub-js'; import React, { Component } from 'react'; export default class Search extends Component { search = () =>{ //获取用户的输入(连续解构赋值+重命名) const {keywordElement:{value:keyword}} = this //发送请求前通知List更新状态 PubSub.publish('atguigu',{isFirst:false,isLoading:true}) //发送网络请求 axios.get(`http://localhost:3000/api1/search/users?q=${keyword}`).then( response =>{ //请求成功后通知List更新状态 PubSub.publish('atguigu',{isLoading:false,users:response.data.items}) }, error =>{ //请求失败后通知List更新状态 PubSub.publish('atguigu',{isLoading:false,err:error.message}) } ) } render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索Github用户</h3> <div> <input ref={c => this.keywordElement = c} type="text" placeholder="输入关键词点击搜索"/> <button onClick={this.search}>搜索</button> </div> </section> ); } }
浙公网安备 33010602011771号