我有一个没有设置为组件的React页面。我希望使用React Hooks,如useEffect或任何其他建议。本质上,我需要清除我的超时。
const ExamplePage = ({
test1, test2, test3
}: Props) => {
const setClipboardTimer = (index, copied, show, delay) => {
const timer = setTimeout(() => {
setClipboardData(index, copied, show);
}, delay);
// How can I clear my timer on componentWillUnmount
};
const copyToClipboard = (copy, index) => {
copyTextToClipboard(copy);
setClipboardData(index, true, true);
setClipboardTimer(index, true, false, 2500);
setClipboardTimer(index, false, true, 3000);
};
};发布于 2019-07-25 09:23:09
由于我不知道其他函数(如copyTextToClipboard、setClipboardData ...etc)在状态方面的作用,更容易利用和测试计时器的方法是使用组件类。
例如,这是一个简单的组件类,它将渲染延迟5秒:
class Timer extends Component {
state = { requestTimeout: false };
// **optional** only rerenders the component if the requestTimeout state has been changed
// this ensures that other state/props changes and/or a parent component
// that has its own updating state, won't update this component
shouldComponentUpdate = (nextProps, nextState) =>
nextState.requestTimeout !== this.state.requestTimeout);
// if the component unloads before the 5000ms timeout, clear it
componentWillUnmount = () => this.clearTimer();
// a class field to clear the timer that was set in this.requestTimeout
clearTimer = () => clearTimeout(this.requestTimeout);
// a class field to update state and clear the timeout
requestTimedout = () =>
this.setState({ requestTimeout: true }, () => this.clearTimer());
// a class field to set this.requestTimeout to a timer that will trigger
// this.requestTimedout after a 5000ms delay
setRequestTimer = () =>
this.requestTimeout = setTimeout(this.requestTimedOut, 5000);
// if requestTimeout state is true (?) show hello (:) else show loading
render = () => this.state.requestTimeout ? <p>Hello</p> : <p>Loading...</p>
}当你开始处理钩子时,当一个挂载的功能组件在计时器仍在运行时更新时,你需要一种方法来持久化相同的计时器(否则,每次功能组件重新渲染时,它都会继续生成新的计时器)。
例如,我有一个涉及使用setIterval的演示here。正如您所看到的(单击源< >按钮),当功能组件的状态被更新时,它涉及到利用useRef对象来保持相同的setInterval计时器。然后,我利用几个回调函数来设置/暂停/清除间隔。此外,它还利用useEffect钩子检查它是否仍在运行,如果还在运行,它将在return语句中将其清除。
简而言之,虽然您可以使用setTimeout在我的setIterval钩子演示中实现相同的功能,但我发现类更易于使用和理解(特别是当状态正在更新并且需要同步处理时)。
https://stackoverflow.com/questions/57192644
复制相似问题