Axios——用于进行http request
https://github.com/axios/axios#typescript
安装Axios
npm install axios --save
Axios+Promise
import axios from 'axios';
componentDidMount(){
//get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response=>{
console.log(response);
});
//promise保证在get操作完成后执行.then操作
}
Redering Fetch data
state中建立array保存传入的内容;
将传入的array用map变为array of < Post />;
将此放入JSX中;
import React, { Component } from 'react';
import Post from '../../components/Post/Post';
import FullPost from '../../components/FullPost/FullPost';
import NewPost from '../../components/NewPost/NewPost';
import './Blog.css';
import axios from 'axios';
class Blog extends Component {
state={
posts:[]
}
componentDidMount(){
//get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response=>{
this.setState({posts:response.data});
});
//promise保证在get操作完成后执行.then操作
}
render () {
const posts = this.state.posts.map( //转为array
post=>{
return <Post title={post.title} key={post.id}/>
}
);
return (
<div>
<section className="Posts">
{posts}
</section>
<section>
<FullPost />
</section>
<section>
<NewPost />
</section>
</div>
);
}
}
export default Blog;
Tranforming data——处理get到的数据
将得到的response取前4;
使用map添加一个author属性;
componentDidMount(){
//get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response=>{
const posts=response.data.slice(0,4);
const updatedPosts = posts.map(post=>{
return {
...post,
author:'JQ'
};
})
this.setState({posts:updatedPosts});
});
//promise保证在get操作完成后执行.then操作
}
Fetching data on update
每次选中一个post,进行get得到该data;
注意点
使用didupdate——配合setstate,会进入死循环;
因为setstate对state进行了改变,引起了re-render,调用update,而update又调用setstate……;
故需要加入条件判断——防止死循环
componentDidUpdate(){
if(this.props.id){
if( !this.state.loadedPost||(this.state.loadedPost && this.state.loadedPost.id !==this.props.id)){
axios.get(`https://jsonplaceholder.typicode.com/posts/${this.props.id}`)
.then(response=>this.setState({loadedPost:response.data}));
}
};
}
Posting data
Axios.post(url,data);
postDataHandler=()=>{
const post={
title:this.state.title,
body:this.state.content,
author:this.state.author
};
Axios.post('https://jsonplaceholder.typicode.com/posts',post). //加入要传入的data
then(response=>{
console.log(response);
});
}
Delete
deletePostHandler=()=>{
axios.delete(`https://jsonplaceholder.typicode.com/posts/${this.props.id}`).then(response=>console.log(response));
}
Catch Error
componentDidMount(){
//get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
axios.get('https://jsonplaceholder.typicode.com/postsss')
.then(response=>{
const posts=response.data.slice(0,4);
const updatedPosts = posts.map(post=>{
return {
...post,
author:'JQ'
};
})
this.setState({posts:updatedPosts});
})
.catch(err=>console.log(err));
//promise保证在get操作完成后执行.then操作
}
Interceptor ——Execute code globally
可以对所有component 的requset和response进行操作;
axios.interceptors.request.use(requset=>{
console.log(requset);
return requset;
},error=>{
console.log(error);
return Promise.reject(error);
});
axios.interceptors.response.use(response=>{
console.log(response)
return response;
},error=>{
console.log(error);
return Promise.reject(error);
});
Get rid of an interceptor
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
https://github.com/axios/axios#interceptors
Setting a Default global configuration
设置全局的默认url;
后面get,post等只需要在baseURL 的基础上写url即可;
axios.defaults.baseURL="https://jsonplaceholder.typicode.com/";
axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
axios.defaults.headers.post['Content-Type'] ='application/json';
进行局部default
在别的js中import该instance,即可实现局部default;
import axios from 'axios';
const instance =axios.create({
baseURL:'https://jsonplaceholder.typicode.com/'
});
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN 123321';
export default instance;