【发布时间】:2019-11-23 04:08:05
【问题描述】:
我一直在学习 React,我读到从 useEffect 返回的函数是为了进行清理,React 在组件卸载时执行清理。
所以我对其进行了一些试验,但在以下示例中发现,每次重新渲染组件时都会调用该函数,而不是仅在从 DOM 卸载时调用该函数,即每次组件时调用 console.log("unmount");重新渲染。
这是为什么呢?
function Something({ setShow }) {
const [array, setArray] = useState([]);
const myRef = useRef(null);
useEffect(() => {
const id = setInterval(() => {
setArray(array.concat("hello"));
}, 3000);
myRef.current = id;
return () => {
console.log("unmount");
clearInterval(myRef.current);
};
}, [array]);
const unmount = () => {
setShow(false);
};
return (
<div>
{array.map((item, index) => {
return (
<p key={index}>
{Array(index + 1)
.fill(item)
.join("")}
</p>
);
})}
<button onClick={() => unmount()}>close</button>
</div>
);
}
function App() {
const [show, setShow] = useState(true);
return show ? <Something setShow={setShow} /> : null;
}
【问题讨论】:
标签: javascript reactjs react-hooks use-effect