【发布时间】:2018-12-02 10:23:16
【问题描述】:
我收到以下错误:
警告:无法在未安装的设备上调用 setState(或 forceUpdate) 零件。这是一个无操作,但它表明您的内存泄漏 应用。要修复,取消所有订阅和异步任务 在 componentWillUnmount 方法中。 在 ViewMessage 中(由 Route 创建)
这里是有问题的组件,如您所见,没有componentWillUnmount:
class ViewMessage extends React.Component{
state={
message: {},
messageId: '',
redirect: false,
reply: false
}
static getDerivedStateFromProps(props, state){
if(props.location.state){
return { messageId: props.location.state.id };
}else{
return { redirect: true}
}
}
componentDidMount(){
this.getMessage()
}
getMessage = () => {
this.setState({_loading: true});
axios({
method: 'get',
url: 'http://localhost:8080/getMessage',
params: {
id: this.state.messageId
},
withCredentials: true
}).then((result) => {
this.setState({message: result.data[0], _loading: false});
})
}
handleReply = () => {
if(this.state.reply){
this.setState({reply: false});
}else{
this.setState({reply: true});
}
}
render(){
if(this.state.redirect){
return(
<Redirect to='/messages' />
)
}
return(
<Container>
{this.state.loading ? <Loader active /> : <div></div>}
<div style={{float: 'right'}}>
{this.state.message.date}
</div>
From: {this.state.message.senderName}
<Divider />
Subject: {this.state.message.subject}
<Divider />
{this.state.message.text}
<Divider />
<Button icon='reply' onClick={this.handleReply}/>
{this.state.reply ? <Composer recipient={this.state.message.senderName}/> : <div></div>}
</Container>
)
}
}
export default ViewMessage;
添加以下行时出现错误,删除后消失:
if(this.state.redirect){
return(
<Redirect to='/messages' />
)
}
我在渲染方法中做错了吗?
【问题讨论】:
-
您是否在 ajax 调用的响应返回之前重定向?从错误消息中,听起来您在卸载组件后尝试设置状态,而我看到的唯一可能的地方是在您的 ajax 调用之后的
.then()。
标签: reactjs