axios的使用及API接口的封装
api/config.js
import axios from 'axios'
// 给所有axios请求设置基础的域名
// axios.defaults.baseURL = 'http://localhost:3000'
//用axios.create可以创建axios的实例,允许不同实例有不同配置
const axios1 = axios.create({
baseURL: 'https://cnodejs.org/api/v1',
// 请求超时的时间
timeout: 5000
});
// const axios2 = axios.create({
// baseURL: 'http://www.test.com',
// timeout: 5000
// });
//添加请求拦截器,会在发起请求之前执行相应的需求
axios1.interceptors.request.use(function (config) {
// console.log('我是请求拦截器');
let token = localStorage.getItem("token")
if (token){
config.headers.common['Authorization'] = 'Bearer ' + token;
}
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// //添加响应拦截器,会在返回数据后先执行相应的需求
axios1.interceptors.response.use(function (response) {
console.log('我是响应拦截器');
// Do something with response data
return response;
}, function (error) {
// Do something with response error
console.log('error',error.status);
return Promise.reject(error);
});
export default axios1
api/http.js
import axios1 from './config'
//获取主题
export function getTopics(type) {
return axios1({
url: '/topics',
method: 'get',
data: {
params: {
type
}
}
})
}
在组件中调用接口
async getData(type) {
try {
let res = await getTopics(type)
this.setState({
list: res.data.data,
loading: false
})
} catch (error) {
console.log('Request Failed', error);
}
}
componentDidMount() {
//请求数据
this.getData('good')
}
//切换标签
toggle(index) {
this.setState({
curIndex: index,
loading: true
})
let type = this.state.tabList[index].type
//请求数据
this.getData(type)
}
react devtool的安装和使用
- 极简插件: https://chrome.zzzmh.cn/
- 搜"react" 下载 "React Developer Tools 开发工具"
- 解压后,把*.crx扩展名改为zip,再解压
- 打开chrome浏览器, 右上角,菜单--> 更多工具 -> 扩展程序 --> 打开"开发者模式" ---> 加载已解压的扩展程序->选择刚才的文件夹即可安装devtools
- 重启chrome,打开react项目,即可在开发者工具最右侧看到新增的"components",可查看组件结构和props,state
楼层导航的思路
import React, { Component } from 'react';
import './Elevator.css'
class Elevator extends Component {
constructor(props) {
super(props);
this.state = {
}
}
scroll(){
console.log(document.documentElement.scrollTop);
}
componentDidMount(){
let floorEl = document.querySelectorAll(".floor")
this.listHeight = [...floorEl].map(item=>{
return item.offsetTop
})
window.addEventListener("scroll",this.scroll)
}
scrollTo(index){
window.scrollTo({
behavior: "smooth",
top: this.listHeight[index]
})
}
render() {
return (
<div>
<button onClick={()=>this.scrollTo(2)}>到达floor3</button>
<div className="floor">floor1</div>
<div className="floor">floor2</div>
<div className="floor">floor3</div>
<div className="floor">floor4</div>
<div className="floor">floor5</div>
</div>
);
}
}
export default Elevator;