gpt4 book ai didi

javascript - 卸载组件时在 setState 上 react 警告

转载 作者:行者123 更新时间:2023-11-29 21:00:41 26 4
gpt4 key购买 nike

当我执行以下代码(见下面的代码片段)时,我收到警告:

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 上 react 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com