【发布时间】:2021-04-29 08:08:22
【问题描述】:
我正在尝试捕获用户的点击次数。 我希望每 15 分钟发送一次 api, 我在 useEffect 中使用 setinterval 来实现这一点,但问题是即使状态在外部发生变化,但在 setinterval 内部却没有。 setinterval 只是给出初始默认值。
这里是代码 -
const Agent = (props: RouteComponentProps) => {
const [clicks, setClicks] = useState(0);
const handleOnIdle = () => {
console.log("user is idle");
console.log("last active", new Date(getLastActiveTime()));
console.log("total idle time: ", getTotalIdleTime() / 1000);
};
const handleOnActive = () => {
console.log("user is active");
console.log("time remaining", getRemainingTime());
};
const handleOnAction = () => {
console.log("user did something", clicks);
setClicks(clicks + 1);
};
const {
getRemainingTime,
getLastActiveTime,
getTotalIdleTime,
} = useIdleTimer({
timeout: 10000,
onIdle: handleOnIdle,
onActive: handleOnActive,
onAction: handleOnAction,
debounce: 500,
});
useEffect(() => {
let timer = setInterval(
() => alert(`user clicked ${clicks} times`),
1000 * 30
);
return () => {
clearInterval(timer);
setClicks(0);
};
}, []);
return (
<AgentLayout>
<div className="dashboard-wrapper py-3">
<Switch>
<Redirect
exact
from={`${props.match.url}/`}
to={`${props.match.url}/home`}
/>
<Route path={`${props.match.url}/home`} component={Home} />
<Route
path={`${props.match.url}/lead-details`}
component={leadDetails}
/>
<Route
path={`${props.match.url}/fill-details`}
component={FillDetails}
/>
<Route
path={`${props.match.url}/my-desktime`}
component={MyDesktime}
/>
<Redirect to="/error" />
</Switch>
</div>
</AgentLayout>
警报提示 用户点击了 0 次
【问题讨论】:
标签: javascript reactjs react-hooks setinterval