我想要setInterval
componentWillUnmount
,componentDidMount() {
setInterval(this.refreshTime, 1000);
}
componentWillUnmount() {
clearInterval(this.refreshTime);
console.log('cleared interval');
}
。
refreshTime
这是我refreshTime = () => {
this.setState({
currentTime: this.renderCurrentTime()
});
}
的好措施:
console.log
setState
日志,但是一旦组件卸载,我仍然会收到warning.js?8a56:36 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.
错误。
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Canvas HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">
<TabControl Height="279" Canvas.Left="10" Canvas.Top="10" Width="477">
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5">
<ListView Name="lv1" Margin="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="110" Width="471">
<ListViewItem>
<CheckBox >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Apple"/>
</StackPanel>
</CheckBox>
</ListViewItem>
<ListViewItem>
<CheckBox >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Orange"/>
</StackPanel>
</CheckBox>
</ListViewItem>
</ListView>
<Button Content="Copy" Width="100" Height="25" Click="Button_Click"/>
<ListView Name="lv2" HorizontalAlignment="Left" VerticalAlignment="Bottom" Height="110" Width="471"/>
</Grid>
</TabItem>
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</TabItem>
</TabControl>
</Canvas>
</Grid>
想法?
答案 0 :(得分:1)
您需要存储setInterval的返回值并清除:
componentDidMount() {
this.refreshInterval = setInterval(this.refreshTime, 1000);
}
componentWillUnmount() {
clearInterval(this.refreshInterval);
console.log('cleared interval');
}
答案 1 :(得分:0)
您没有以正确的方式使用clearInterval。需要将setInterval
的返回值传递给相应的方法clearInterval
,您需要清除该区间。
var intervalID = setInterval(func, delay[, param1, param2, ...]);
clearInterval(intervalID );