【发布时间】:2019-05-30 13:35:03
【问题描述】:
我正在 componentDidMount 中获取数据并更新状态,并且出现了著名的警告:
无法对未安装的组件执行 React 状态更新。这是 无操作,但它表明您的应用程序中存在内存泄漏。修理, 取消所有订阅和异步任务 componentWillUnmount 方法。
state = {
post: null
}
render() {
console.log(this.props.postId)
if (this.props.post) {
return (
<div>
<h3> {this.state.post.postTitle} </h3>
<p> {this.state.post.postBody} </p>
</div>
);
} else {
return <Redirect to="/blog" />
}
}
componentDidMount() {
this._isMounted = true;
axios
.get('https://jsonplaceholder.typicode.com/posts/' + + this.props.postId)
.then((response) => {
let post = {
id: response.data.id,
postTitle: response.data.title,
postBody: response.data.body
}
this.setState((prevState,props)=>{
console.log('post',post)
console.log('prevState',prevState)
console.log('props',props)
})
})
.catch((e) => {
console.log('error', e)
})
}
}
是什么导致了这个警告?获取数据和更新状态的最佳方法是什么?
【问题讨论】:
-
组件可能会在通过
axios的 Ajax 请求完成之前再次卸载。
标签: reactjs