从对象呈现的React组件不会被卸载



我有以下代码,其中我需要在卸载每个组件步骤时运行清理。我在每个步骤上都设置了useEffect,以检查组件是否已卸载。当父级获得一个新的currentStep时,它会交换当前活动的组件,但清除操作永远不会运行。我想知道这是否与从对象渲染的组件的性质有关

const Step1 = () => {
useEffect(() => {
console.log("doing things here");

return () => {
console.log("clean-up should happen here but this won't print")
}
}, []}
}
const StepMap = {
step1: <Step1/>
step2: <Step2/>
step3: <Step3/>
}

const Parent = ({ currentStep }) => {
return (
<div>
{ StepMap[currentStep] }
</div>
)
}

或者,这段代码确实运行了清理,但我确实找到了以前的清理

const Parent = ({ currentStep }) => {
return (
<div>
{ currentStep === "step1" && StepMap[currentStep]}
{ currentStep === "step2" && StepMap[currentStep]}
</div>
)
}

为什么第一种方法不起作用?有没有一种方法可以让它像第二种一样工作,同时保持更清洁的实现?

如果您想在jsx中编写javascript,我们必须在{}大括号中编写,如下所示:

import React, { useEffect, useState } from "react";
const Step1 = () => {
useEffect(() => {
console.log("Step1 doing things here");
return () => {
console.log("Step1 clean-up should happen here but this won't print");
};
}, []);
return <div>stepOne</div>;
};
const Step2 = () => {
useEffect(() => {
console.log("Step2 doing things here");
return () => {
console.log("Step2 clean-up should happen here but this won't print");
};
}, []);
return <div>steptw0</div>;
};
const Step3 = () => {
useEffect(() => {
console.log("Step3 doing things here");
return () => {
console.log("Step3 clean-up should happen here but this won't print");
};
}, []);
return <div>stepthree</div>;
};
export const StepMap = {
step1: <Step1 />,
step2: <Step2 />,
step3: <Step3 />,
};
export const Parent = ({ currentStep }) => {
return <div>{StepMap[currentStep]}</div>;
};
const App = () => {
const [steps, setSteps] = React.useState("step1");
React.useEffect(() => {
setTimeout(() => setSteps("step2"), 5000);
setTimeout(() => setSteps("step3"), 15000);
}, []);
return <Parent currentStep={steps} />;
};
export default App;

最新更新