一、PubSubJS的使用
- 工具库: PubSubJS
- 下载: npm install pubsub-js --save
- 使用:
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="输入关键词点击搜索"/> 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={{'100px'}}/> 37 </a> 38 <p className="card-text">{userObj.login}</p> 39 </div> 40 ) 41 }) 42 } 43 </div> 44 ) 45 } 46 }
三、扩展Fetch
1. 文档
2. 特点
- fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
- 老版本浏览器可能不支持
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 })