前三章在这里:React学习记录 ---第一章-CSDN博客
消息订阅-发布机制
介绍
父子组件间通信方便,但兄弟组件间通信并不方便,要借助父组件,于是...有了消息订阅与发布
举个例子!
订阅报纸:1、交钱,说好地址,订阅哪一种报纸;2、邮递员送报纸
订阅消息:1、消息名;2、发布消息
工具库:PubSubJS
下载:npm install pubsub-js --save
使用:1.import PubSub from 'pubsub-js' //引入
2.PubSub.subscribe('delete', function(data){ }); //订阅
3.PubSub.publish('delete', data) //发布消息
举个例子!下面都是类组件,AB为兄弟组件
A组件
state = { //初始化状态
users:[], //users初始值为数组
isFirst:true, //是否为第一次打开页面
isLoading:false,//标识是否处于加载中
err:'',//存储请求相关的错误信息
}
componentDidMount(){
this.token = PubSub.subscribe('atguigu',(_,stateObj)=>{
this.setState(stateObj)
})
}
componentWillUnmount(){
PubSub.unsubscribe(this.token)
}
B组件
PubSub.publish('atguigu',{isFirst:false,isLoading:true})
axios.get(`/api1/search/users?q=${keyWord}`).then(
response => {
//请求成功后通知List更新状态
PubSub.publish('atguigu',{isLoading:false,users:response.data.items})
},
error => {
//请求失败后通知App更新状态
PubSub.publish('atguigu',{isLoading:false,err:error.message})
}
)
}
总结:先订阅,再发布(隔空对话);
适用于任何组件间通信;
记得要在组件的componentWillUnmount中取消订阅
fetch
发送ajax请求有几种方式:
xhr
jQuery、axios都是对xhr的封装,需要下载,其中axios是promise风格
fetch:原生函数,不再使用xhr对象提交ajax请求,不是第三方库,无需下载,也是promise风格,能解决回调地狱问题,与xhr并列,但是目前fetch使用率不高,因为老版本浏览器可能不支持
推荐学习博客:https://segmentfault.com/a/1190000003810652
https://github.github.io/fetch/
所谓”关注分离“就是不会一下子把数据都发给你
举个fetch发get请求的例子,分两步:连接服务器+获取数据,fetch能统一处理错误
//.then能链式调用是因为其返回值仍然是promise实例
fetch(`/api1/search/user?q=${keyword}`).then(
response => {console.log('联系服务器成功了');
return response.json()
}
/*error => {console.log(';联系服务器失败了',error);
return new Promise(()=>{})
}*/
).then(
response => {console.log('获取数据成功',response);},
//error => {}
).catch(
(error)=>{console.log(error)}
)
优化
search = async()=>{
try{
const res = await fetch(`/api1/search/user?q=${keyword}`)
const data = await res.json()
}catch(err){
console.log('错了')
}
}
post
fetch(url, {
method: "POST",
body: JSON.stringify(data),
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
})
补充知识点:解构赋值+重命名
let obj = {a:{b:1}}
const {a} = obj; //传统解构赋值
const {a:{b}} = obj; //连续解构赋值
const {a:{b:value}} = obj; //连续解构赋值+重命名
关注我,不迷路!
会不定时为大家更新优质内容!收藏起来方便随时查看!