【发布时间】:2023-04-04 16:32:01
【问题描述】:
我正在尝试构建一个带有钩子的功能组件,它在卸载时只调用一次函数。在这个函数中,我需要访问组件当前状态变量。
This codesandbox illustrates the core problem I'm facing
我知道我可以在 useEffect 依赖数组中传递状态变量,但在我的实际示例中,要求效果仅在组件卸载时调用一次,并将其添加到数组中会导致它在每次渲染时调用。
我还尝试了 useCallback、useRef 到 state 变量并搜索了类似的用例和示例但没有成功,我觉得我错过了一些东西。
有没有办法同时满足这两个要求(只调用一次并访问当前状态变量)?
这也是我的示例代码。按钮安装/卸载计数器,我想要实现的是,计数器的最后一个值在消失时打印。
import * as React from "react";
import "./styles.css";
import { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
return () => {
// this should print the counters current value
console.log("Count was " + count + " when counter disappeard!");
};
}, []); // Empty because effect should only run when component unmounts
const handleClick = () => {
setCount(count + 1);
};
return <button onClick={handleClick}>{count}</button>;
};
export default function App() {
const [showCounter, setShowCounter] = useState(true);
// mount/unmount the counter
const handleClick = () => {
setShowCounter(!showCounter);
};
return (
<div className="App">
<button onClick={handleClick}>Show/Hide counter</button>
{showCounter && <Counter />}
</div>
);
}
如果有人知道解决这个问题的方法,我会非常高兴。
【问题讨论】:
标签: reactjs react-hooks