gpt4 book ai didi

reactjs - 使用 axios 取消卸载时的异步请求

转载 作者:行者123 更新时间:2023-12-03 13:37:45 26 4
gpt4 key购买 nike

我有多个组件 axios一些获取请求的插件。我需要一些帮助来取消在 React JS 中组件卸载事件上使用 axios 的所有 xhr 请求。但 axios 取消代码不起作用。它的返回给我cancel()不是一个函数错误。

代码示例:-

import axios from 'axios';


var CancelToken = axios.CancelToken;
var cancel;

axios.get('abc/xyz', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});

// cancel the request
cancel();

请帮助我在 axios 中实现取消请求。

谢谢。

最佳答案

这很简单。在 componentDidMount 中创建请求,并在 componentWillUnmount 中取消请求。将 url 替换为现有的 JSON 文件,此代码段将按预期工作:

class MyComponent extends Component {
constructor (props) {
super(props)

this.state = {
data: []
}
}

componentDidMount () {
this.axiosCancelSource = axios.CancelToken.source()

axios
.get('data.json', { cancelToken: this.axiosCancelSource.token })
.then(response => {
this.setState({
data: response.data.posts
})
})
.catch(err => console.log(err))
}

componentWillUnmount () {
this.axiosCancelSource.cancel('Axios request canceled.')
}

render () {
const { data } = this.state

return (
<div>
{data.items.map((item, i) => {
return <div>{item.name}</div>
})}
</div>
)
}
}

关于reactjs - 使用 axios 取消卸载时的异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46110082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com