react 消息订阅-发布机制(解决兄弟组件通信问题)
生活随笔
收集整理的這篇文章主要介紹了
react 消息订阅-发布机制(解决兄弟组件通信问题)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
消息訂閱-發布機制
1)import PubSub from ‘pubsub-js’ //引入
2)PubSub.subscribe(‘delete’, function(data){ }); //訂閱
3)PubSub.publish(‘delete’, data) //發布消息
App組件:
Search組件:
import React, {Component} from 'react'; import PubSub from 'pubsub-js' import axios from "axios";class Search extends Component {search = () => {// 獲取用戶的輸入(連續解構賦值+重命名)const {keyWordElement: {value: keyword}} = this// 發送請求前通知List更新狀態// this.props.updateAppState({isFirst: false, isLoading: true})PubSub.publish('zep', {isFirst: false, isLoading: true})// 發送網絡請求axios.get(`https://api.github.com/search/users?q=${keyword}`).then((response) => {// 請求成功后通知List更新狀態// this.props.updateAppState({isLoading: false, users: response.data.items})console.log('Search組件發布消息')PubSub.publish('zep', {isLoading: false, users: response.data.items})},(error) => {// this.props.updateAppState({isLoading: false, err: error.message})PubSub.publish('zep', {isLoading: false, err: error.message})})}render() {return (<section className="jumbotron" style={{textAlign: "center"}}><h3 className="jumbotron-heading">搜索github用戶</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/> <button onClick={this.search}>搜索</button></div></section>);} }export default Search;List組件:
import React, {Component} from 'react'; import PubSub from 'pubsub-js' import './index.css'class List extends Component {state = {// 初始化狀態users: [], // users初始值為數組isFirst: true, // 是否為第一次打開頁面isLoading: false, // 標識是否處于加載中err: '' // 存儲請求相關的錯誤信息}componentDidMount() {// 訂閱消息this.token = PubSub.subscribe('zep', (msg, stateObj) => {console.log('List組件訂閱消息', 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 className="card" key={userObj.id}><a href={userObj.html_url} rel="noreferrer" target="_blank"><img alt="avatar" src={userObj.avatar_url} style={{width: '100px'}}/></a><p className="card-text">{userObj.login}</p></div>)})}</div>);} }export default List;總結
以上是生活随笔為你收集整理的react 消息订阅-发布机制(解决兄弟组件通信问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: delphi 调用php接口_爱站权重查
- 下一篇: 二、MySQL连接查询学习笔记(多表连接