结合案例:github搜索案例
结果如下图
1.父容器代码
import React, { Component } from 'react'
import Search from './components/Search'
import List from './components/List'
export default class App extends Component { render ( ) { return ( < div className= "container" > < Search/ > < List/ > < / div> ) }
}
2.搜索Search子模块代码(发布消息)
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios' export default class Search extends Component { search = ( ) => { const { keyWordElement : { value : keyWord} } = this PubSub. publish ( 'atguigu' , { isFirst : false , isLoading : true } ) axios. get ( ` /api1/search/users?q= ${ keyWord} ` ) . then ( response => { PubSub. publish ( 'atguigu' , { isLoading : false , users : response. data. items} ) } , error => { 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= "输入关键词点击搜索" / > & nbsp; < button onClick= { this . search} > 搜索< / button> < / div> < / section> ) }
}
3.展示Lisi子模块代码(订阅消息)
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css' export default class List extends Component { state = { 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 . statereturn ( < 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 rel= "noreferrer" href= { userObj. html_url} target= "_blank" > < img alt= "head_portrait" src= { userObj. avatar_url} style= { { width : '100px' } } / > < / a> < p className= "card-text" > { userObj. login} < / p> < / div> ) } ) } < / div> ) }
}
发布订阅分析
在Search子模块中发布消息,用PubSub.publish中进行发布消息,在List子模块中订阅消息,拿到数据进行展示 使用步骤