React应用与ajax【第三章、第四章】
github用户搜索 案例
解决跨域
- package.json 里添加 proxy, “proxy”: “http://localhost:5000"
连续解构赋值
1 | // 正常写法 |
消息订阅——发布机制 pubsub-js
pubsub-js作用:用于任意页面之间的通信(订阅发布:先发布后订阅)
用法:
1.发布 PubSub.publish(‘switchMusic’, type);
2.订阅 PubSub.subscribe(‘switchMusic’, (msg, data) => {
console.log(data)
})
PubSub.subscribe会触发多次(每订阅一次,数据就会累加,需求只需订阅一次时使用)
3.取消订阅 PubSub.unsubscribe('switchMusic')
React【componentWillUnmount】
1 | componentDidMount() { |
React ajax【第四章】
- xhr 和 fetch
- xhr 封装的库:axios实现异步加载
- fetch:fetch实现异步加载
fetch发送请求 (关注分离的设计思想)
1
2
3
4
5
6
7
8
9
10// try catch 获取await的错误情况
try {
let data = await fetch(`https://api.github.com/search/users?q=${keyWord}`)
let response = await data.json()
PubSub.publish('data', { isLoading: false, users: response.items });
console.log(response);
} catch (error) {
console.log(error);
PubSub.publish('data', {isLoading:false,err:error.message});
}1
2
3
4
5
6
7
8
9// axios实现异步加载
axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
response => {
PubSub.publish('data', {isLoading:false,users:response.data.items});
},
error => {
PubSub.publish('data', {isLoading:false,err:error.message});
}
)