当我执行以下代码(参见下面的代码片段)时,我收到警告:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Blinker component.
我的 Mounter 类下的 componentWillUnmount() 方法是否做错了什么?谢谢!
class Blinker extends React.Component {
constructor(props) {
super();
this.state = {
appear: true
}
this.blinker = this.blinker.bind(this);
}
blinker() {
this.setState({appear: !this.state.appear });
}
componentDidMount() {
setInterval(this.blinker, 300)
}
render() {
return (
<div>
{ (this.state.appear) && "xxx" }
</div>
);
}
}
class Mounter extends React.Component {
constructor(props) {
super();
this.state = {
render: true
};
this.interval = null;
}
componentDidMount() {
this.interval = setTimeout( () =>
this.rendering(), 1500
);
}
componentWillUnmount() {
clearInterval(this.interval);
}
rendering() {
this.setState({ render: !this.state.render });
}
render() {
return (
<div>
<h1>
{ this.state.render && <Blinker /> }
</h1>
</div>
);
}
}
ReactDOM.render(<Mounter />, app);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
最佳答案
清除this.interval
并在设置状态之前检查它。这将防止组件卸载后设置状态。
componentWillUnmount() {
clearInterval(this.interval);
this.interval = null; // clear
}
rendering() {
// this.interval will be null when unmounting so avoid setting state:
if (this.interval) {
this.setState({
render: !this.state.render
});
}
}
关于javascript - 卸载组件时对 setState 发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635649/