reactJS如何停止监听Ajax请求

编程入门 行业动态 更新时间:2024-10-25 14:32:15
本文介绍了reactJS如何停止监听Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在componentdidmount中有一个ajax调用.然后在ajax promise中设置setState.

I have ajax call in componentdidmount. And and then setState inside the ajax promise.

代码是这样的

componentDidMount(){ axios.post('mydomian/item/',this.state) .then(function (response) { const res = response.data if (res.status === 'OK') { this.setState({items :res.list}) }else{ console.log('can not load data', response) } }.bind(this)) } componentWillUnmount(){ how to stop everything about axios? }

当我导航到其他路线时,这会导致错误无法在未安装的组件上设置状态".

This causes error 'can not setstate on an unmounted component', when I navigate to other route.

所以我认为我应该做的是在componentwillunmount中删除axios监听器.你会怎么做?

So I think what I should do is remove axios listener in the componentwillunmount. How to would you do it?

推荐答案

一个非常简单的解决方案可以是在unmount上设置一个标志,并在promise分辨率内使用它,例如:

A very simple solution could be to set a flag on unmount and utilize it within the promise resolution, like so:

componentDidMount(){ axios.post('mydomian/item/',this.state) .then(function (response) { if (this.unmounted) return; const res = response.data if (res.status === 'OK') { this.setState({items :res.list}) }else{ console.log('can not load data', response) } }.bind(this)) } componentWillUnmount(){ this.unmounted = true; }

更多推荐

reactJS如何停止监听Ajax请求

本文发布于:2023-11-12 18:48:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:reactJS   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!