我是React的新手,我有一个问题,重定向路由器和已安装的组件,因为我收到了警告。请查看may组件:
class Activation extends React.Component {
constructor(props){
super()
this.token = props.match.params.id
this.state = {
fadeOn: false
}
}
componentDidMount(){
fetch('/api/activate/' + this.token, {
method: 'PUT'
}).then((response) => response.json())
.then((message)=>{
if(message.success){
this.setState({
fadeOn: true,
msg: message.message
})
} else {
this.setState({
fadeOn: true,
errMsg: message.message
})
}
})
}
render(){
return (
<Grid>
<Row>
<img className="rabbit" src={rabbit}/>
<Fade in={this.state.fadeOn}>
{this.state.msg?
<Alert bsStyle="success" className="activeAlert">{this.state.msg}</Alert>
:
<Alert bsStyle="danger" className="activeAlert">{this.state.errMsg}</Alert>
}
</Fade>
</Row>
<Redirect to="/"/>
</Grid>
)
}
}
export default Activation
路径中的组件=&#34; /&#34;
class Users extends Component {
render() {
return (
<div>
<h1>Users page!!!</h1>
</div>
);
}
}
export default Users;
我的目标是在激活他的帐户后重定向用户。一切正常,但重定向后,我收到以下警告:Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
。你能解释一下我做错了什么,以及我的组件是什么?
答案 0 :(得分:1)
这是因为在初始渲染本身中,您将重定向到&#34; /&#34;然后在componentDidMount中设置状态。所以,
在构造函数中将状态设置为
this.state = {
fadeOn: false,
activationComplete: false ,
}
在fetch的.then
中,您应该将状态设置为
this.setState({
fadeOn: true,
msg: message.message,
activationComplete:true
})
然后,在渲染中,用
替换现有的重定向语句render(){
if(this.state.activationComplete)
return <Redirect to="/"/>
else
return (
<Grid>
<Row>
<img className="rabbit" src={rabbit}/>
<Fade in={this.state.fadeOn}>
{this.state.msg?
<Alert bsStyle="success" className="activeAlert">{this.state.msg}</Alert>
:
<Alert bsStyle="danger" className="activeAlert">{this.state.errMsg}</Alert>
}
</Fade>
</Row>
</Grid>
)
}