React---消息訂閱發佈機制

一、PubSubJS的使用

  1. 工具庫: PubSubJS
  2. 下載: npm install pubsub-js --save
  3. 使用:

1) import PubSub from 'pubsub-js' //引入

2) PubSub.subscribe('delete', function(data){ }); //訂閱

3) PubSub.publish('delete', data) //發佈消息

二、案例

接上一篇github搜索案例改造

1. App.jsx

 1 import React, { Component } from 'react'
 2 import Search from './components/Search'
 3 import List from './components/List'
 4 
 5 export default class App extends Component {
 6     render() {
 7         return (
 8             <div className="container">
 9                 <Search/>
10                 <List/>
11             </div>
12         )
13     }
14 }

 

2. Search.jsx

 1 import React, { Component } from 'react'
 2 import PubSub from 'pubsub-js'
 3 import axios from 'axios'
 4 
 5 export default class Search extends Component {
 6 
 7     search = ()=>{
 8         //獲取用戶的輸入(連續解構賦值+重命名)
 9         const {keyWordElement:{value:keyWord}} = this
10         //發送請求前通知List更新狀態
11         PubSub.publish('msg',{isFirst:false,isLoading:true})
12         //發送網絡請求
13         axios.get(`/api1/search/users?q=${keyWord}`).then(
14             response => {
15                 //請求成功後通知List更新狀態
16                 PubSub.publish('msg',{isLoading:false,users:response.data.items})
17             },
18             error => {
19                 //請求失敗後通知App更新狀態
20                 PubSub.publish('msg',{isLoading:false,err:error.message})
21             }
22         )
23     }
24 
25     render() {
26         return (
27             <section className="jumbotron">
28                 <h3 className="jumbotron-heading">搜索github用戶</h3>
29                 <div>
30                     <input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/>&nbsp;
31                     <button onClick={this.search}>搜索</button>
32                 </div>
33             </section>
34         )
35     }
36 }

3. List.jsx

 1 import React, { Component } from 'react'
 2 import PubSub from 'pubsub-js'
 3 import './index.css'
 4 
 5 export default class List extends Component {
 6 
 7     state = { //初始化狀態
 8         users:[], //users初始值爲數組
 9         isFirst:true, //是否爲第一次打開頁面
10         isLoading:false,//標識是否處於加載中
11         err:'',//存儲請求相關的錯誤信息
12     } 
13 
14     componentDidMount(){
15         this.token = PubSub.subscribe('msg',(_,stateObj)=>{
16             this.setState(stateObj)
17         })
18     }
19 
20     componentWillUnmount(){
21         PubSub.unsubscribe(this.token)
22     }
23 
24     render() {
25         const {users,isFirst,isLoading,err} = this.state
26         return (
27             <div className="row">
28                 {
29                     isFirst ? <h2>歡迎使用,輸入關鍵字,隨後點擊搜索</h2> :
30                     isLoading ? <h2>Loading......</h2> :
31                     err ? <h2 style={{color:'red'}}>{err}</h2> :
32                     users.map((userObj)=>{
33                         return (
34                             <div key={userObj.id} className="card">
35                                 <a rel="noreferrer" href={userObj.html_url} target="_blank">
36                                     <img alt="head_portrait" src={userObj.avatar_url} style={{width:'100px'}}/>
37                                 </a>
38                                 <p className="card-text">{userObj.login}</p>
39                             </div>
40                         )
41                     })
42                 }
43             </div>
44         )
45     }
46 }

 

三、擴展Fetch

1. 文檔

  1. https://github.github.io/fetch/
  2. https://segmentfault.com/a/1190000003810652

2. 特點

  1. fetch: 原生函數,不再使用XmlHttpRequest對象提交ajax請求
  2. 老版本瀏覽器可能不支持

3. 相關API

1) GET請求

1 fetch(url).then(function(response) {
2     return response.json()
3   }).then(function(data) {
4     console.log(data)
5   }).catch(function(e) {
6     console.log(e)
7   });

1) POST請求

1 fetch(url, {
2     method: "POST",
3     body: JSON.stringify(data),
4   }).then(function(data) {
5     console.log(data)
6   }).catch(function(e) {
7     console.log(e)
8   })

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章