具有无限调用的依赖项的useEffect



在从列表中添加/删除项目后,我有一个要隐藏在超时函数中的警报。

useEffect没有清除超时函数,而是以循环结束。

function App() {
const [item, setItem] = useState({
id: "",
name: "",
});
const [list, setList] = useState([]);
const [isEditing, setISEditing] = useState(false);
const [alert, setAlert] = useState({
active: false,
type: "",
});
const addToList = (e) => {
e.preventDefault();
setAlert({ active: true, type: "success" });
let newItem = { id: new Date().getTime().toString(), name: item };
e.preventDefault();
setList([...list, newItem]);
};
const removeFromList = (id) => {
setAlert({ active: true, type: "danger" });
setList(list.filter((item) => item.id !== id));
};
useEffect(() => {
const timeout = setTimeout(() => {
setAlert({ active: false, type: "" });
}, 3000);
return () => clearTimeout(timeout);
}, [alert.active]);

我下面有一个类似的例子,但useEffect并没有出现在循环中,尽管我在useEffect中更改了状态。两者到底有什么区别?

const SingleColor = ({ rgb, weight, index }) => {
const [alert, setAlert] = useState(false);
const hex = rgbToHex(...rgb);
useEffect(() => {
const timeout = setTimeout(() => {
setAlert(false);
}, 3000);
return () => clearTimeout(timeout);
}, [alert]);
return (
<article
className={`color ${index > 10 && "color-light"}`}
style={{ backgroundColor: hex }}
onClick={() => {
setAlert(true);
navigator.clipboard.writeText(hex);
}}
>
<p className="percent-value">{weight}%</p>
<p className="color-value">{hex}</p>
{alert && <p className="alert">Copied to clipboard!</p>}
</article>
);
};
export default SingleColor;

使用alert.active依赖项,每次alert.active更改时,您都要重新触发useEffect。在useEffect中,您正在为alert.active设置一个新值,从而创建一个无限循环。

您应该直接在addToList或remove from list函数的末尾调用超时。如果你想,你可以在一个单独的功能中隔离它

const cancelTimeout = () => {
setTimeout(() => setAlert({ active: false, type: "" }), 3000)
}

并在CCD_ 7和CCD_ 8 结束时调用CCD_

最新更新