大概是这样的代码
$.ajax({ ... success: function(data) { var quote = data[0].media; if (this.isMounted()){ this.setState({ quotes: quote }); } } });
然后浏览器报了这样一个错
this.IsMounted() is not a function
然后我谷歌的找到了其他人的回答
大概是这样的
$.ajax({ ... success: function(data) { var quote = data[0].media; if (this.isMounted()){ this.setState({ quotes: quote }); } }.bind(this); });
或者是这样的
componentDidMount: function(){ $.ajax({ // the method is already bound to the component success: this.onDataReceived }); },onDataReceived: function(data) { var quote = data[0].media; if(this.isMounted()){ this.setState({ quotes: quote }); } }
对比了一下React中文api和阮一峰大神的demo,确实都是这样写的。为啥会错?
随即去翻了React官网的API,原来 isMounted() 这个方法被React废弃掉了,so 不能用这个函数了
然后官网给了一个案例
大概是这个样子的
componentDidMount: function() { this.serverRequest = $.get(this.props.source,function (result) { var lastGist = result[0]; this.setState({ username: lastGist.owner.login,lastGistUrl: lastGist.html_url }); }.bind(this)); },componentWillUnmount: function() { this.serverRequest.abort(); }
官网是这么解释的
When fetching data asynchronously,usecomponentWillUnmount
to cancel any outstanding requests before the component is unmounted.
当异步加载数据的时候, 使用 componentWillUnmount来取消任何未完成的请求 在组件卸载之前
componentWillUnmount()
在组件从 DOM 中移除的时候立刻被调用。
在该方法中执行任何必要的清理,比如无效的定时器,或者清除在componentDidMount
中创建的 DOM 元素
所以我们可以用这个方法替代 isMounted() 来确保该组件是否还是mounted
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。