React Ajax this.IsMounted() is not a function
大概是这样的代码
$.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,use
当异步加载数据的时候, 使用 componentWillUnmount来取消任何未完成的请求 在组件卸载之前 componentWillUnmount()
在组件从 DOM 中移除的时候立刻被调用。 在该方法中执行任何必要的清理,比如无效的定时器,或者清除在 所以我们可以用这个方法替代 isMounted() 来确保该组件是否还是mounted (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |