React
by shuliqi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
const CancelToken = axios.CancelToken;
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
tips: '',
data: null,
}
this.getData = this.getData.bind(this);
}
getData() {
let cancel;
axios.get('https://www.fastmock.site/mock/d867c364f89208a7672e9e9d0a822417/qixiao/iterationinfo', {
cancelToken:new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
})
.then(({ data }) => {
this.setState({
tips: '',
data: data.data,
})
console.log('获得数据:', data.data)
})
.catch((thrown) => {
if (axios.isCancel(thrown)) {
this.setState({ tips: thrown.message})
}
});
// 取消方法`cancel
cancel('手动把请求被取消了');
};
render() {
const {
tips,
} = this.state;
const {
complete,
completeTime,
count,
} = this.state.data || {}
return (
<div>
<button onClick={this.getData}>连续点击</button>
{ tips && (
<div>{tips}</div>
)}
{ this.state.data && (
<div>
我请求到了数据
<br/>
complete :{complete}
<br/>
completeTime: {completeTime}
<br/>
count: {count}
</div>
)}
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))