消息订阅与发布
react中的消息订阅与发布是一种组件间通信的方式,适用于任意组件间通信。包括父子组件,祖孙组件。
一、安装
npm install pubsub-js --save
或者
yarn add pubsub-js
二、使用
1.引入:
import PubSub from 'pubsub-js'
2.订阅:
PubSub.subscribe('delete', function(data){ })
3.发布:
PubSub.publish('delete', data)
代码案例:
发布消息:
import React, {Component} from 'react'
import PubSub from 'pubsub-js'
import axios from "axios";
class Search extends Component {
getMoviesData = () => {
// 发布消息
axios.get('/api1/search/movies?q='+this.keywords.value).then(
response => {
PubSub.publish('data',{list: response.data, isLoading: false})
this.setState({isLoading: false})
},
error => {
PubSub.publish('data', {err: error.message, isLoading: false})
this.setState({isLoading: false})
},
)
}
render() {
return (
<div>
<div>
<input ref={c => this.keywords = c} type="text"/>
<button type="button" id="button-addon2" onClick={this.getMoviesData}>
搜索
</button>
</div>
</div>
);
}
}
export default Search
订阅:
import React, {Component} from 'react'
import PubSub from 'pubsub-js'
class List extends Component {
state = {
list: [],
}
changeState = (msg, data) => {
this.setState(data)
}
componentDidMount() {
// 订阅消息
this.toekn = PubSub.subscribe('data', this.changeState)
}
componentWillUnmount() {
// 取消消息订阅
PubSub.unsubscribe(this.toekn)
}
render() {
const {list} = this.state
return (
<div className="row ">
{
list.map((item)=> {
return (
<div className="col-2" key={item.id}>
<div>{item.title}</div>
</div>
)
})
}
</div>
);
}
}
export default List
注意:一般在组件挂载完后进行消息订阅,在组件将要卸载的时候取消订阅。