我有 App
和 Test
组件。
应用
import "./App.css";
import { React, useState, useEffect} from 'react';
import Test from './Test';
function App() {
const [load, setLoad] = useState(true);
useEffect(() => {
console.log('useEffect called');
})
return (
<div>
{load ? <Test></Test> : null}
<button onClick={() => setLoad(!load)}>Toggle</button>
</div>
);
}
export default App;
测试
import React from 'react'
class Test extends React.Component {
counter = 0;
interval;
componentDidMount() {
console.log('componentDidMount')
this.interval = setInterval(() => {
console.log(this.counter++);
},1000)
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
<h1>test</h1>
</div>
)
}
}
export default Test
当测试组件被破坏时,我想清理间隔
如果我使用类组件
import React from 'react'
class Test extends React.Component {
counter = 0;
interval;
componentDidMount() {
console.log('componentDidMount')
this.interval = setInterval(() => {
console.log(this.counter++);
},1000)
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
<h1>test</h1>
</div>
)
}
}
export default Test
这将在我单击例如清除间隔的 Toggle 组件时起作用。
但是如果我使用功能组件
import React, { useEffect } from 'react'
function Test() {
let counter = 0;
useEffect(() => {
let interval = setInterval(() => {
counter++;
console.log(counter);
return () => {
console.log('interval', interval)
clearInterval(interval);
}
},1000)
})
return (
<div>
<h1>Test</h1>
</div>
)
}
export default Test
然后它不起作用。当测试组件被销毁时,我仍然在控制台中打印间隔
我该如何清理这里?
答案 0 :(得分:1)
您需要在区间下方添加回报。所有 useEffects 清理都是这样发生的:
useEffect((){
//do stuff
return ()=> //clean stuff
}, [])
另外,不要忘记 useEffect 末尾的依赖数组。
答案 1 :(得分:0)
useEffect需要添加return,卸载组件时会用到
import React, { useEffect } from 'react'
function Test() {
let counter = 0;
useEffect(() => {
let interval = setInterval(() => {
counter++;
console.log(counter);
},1000)
return () => {
console.log('interval', interval)
clearInterval(interval);
}
})
return (
<div>
<h1>Test</h1>
</div>
)
}
export default Test