英文:
Unmounting functional components in React
问题
import React, { useState, useEffect } from "react";
function MouseContainer() {
const [seeBox, setSeeBox] = useState(true);
return (
<>
<button onClick={() => setSeeBox(!seeBox)}>Toggle Black Box</button>
{seeBox && <BlackBox></BlackBox>}
</>
);
}
function BlackBox() {
const onBackBoxUnmount = () => {
console.log("清理代码...");
};
useEffect(() => {
return onBackBoxUnmount;
});
return (
<div style={{ backgroundColor: "black", height: 100, width: 100 }}></div>
);
}
export default MouseContainer;
英文:
I am new to React. I am trying out an exercise. In my app I have a button that toggles the appearance of a black box. I want the onBlackBoxUnmount function to be executed when the BackBox component is unmounted. However, I notice that it is executed every time I click the button. What does this happen.
import React, { useState, useEffect } from "react";
function MouseContainer() {
const [seeBox, setSeeBox] = useState(true);
return (
<>
<button onClick={() => setSeeBox(!seeBox)}>Toggle Black Box</button>
{seeBox && <BlackBox></BlackBox>}
</>
);
}
function BlackBox() {
const onBackBoxUnmount = () => {
console.log("clean up code ...");
};
useEffect(() => {
return onBackBoxUnmount;
});
return (
<div style={{ backgroundColor: "black", height: 100, width: 100 }}></div>
);
}
export default MouseContainer;
答案1
得分: 1
You set it up right! It will be executed everytime you unmount your component. But as you said, even when seeBox is FALSE
so I don't think the problem is the component but React StrictMode. Docs > Your components will re-render an extra time to find bugs caused by impure rendering.
This could be the problem. and make it console log twice.
You can find if it is Enabled or not by look at App.tsx (or App.js). If your app is wrapped in StrictMode component. just delete it and check again.
英文:
You set it up right!
It will be executed everytime you unmount your component.
But as you said, even when seeBox is FALSE
so I don't think the problem is the component but React StrictMode.
Docs
> Your components will re-render an extra time to find bugs caused by impure rendering.
This could be the problem. and make it console log twice.
You can find if it is Enabled or not by look at App.tsx (or App.js).
If your app is wrapped in StrictMode component. just delete it and check again.
答案2
得分: 0
你需要在useEffect
中传入一个空的依赖数组,就像这样:
useEffect(() => {
...
}, [])
英文:
You will need to pass in an empty dependency array in the useEffect.
Something like this:
useEffect(() => {
...
}, [])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论