[React] Detect user activity with a custom useIdle React Hoo
发布时间:2020-12-15 20:34:58 所属栏目:百科 来源:网络整理
导读:If the user hasn‘t used your application for a few minutes,you may want to log them out of the application automatically in case they‘ve stepped away from the machine and someone nefarious attempts to use their session. Let‘s checkout h
If the user hasn‘t used your application for a few minutes,you may want to log them out of the application automatically in case they‘ve stepped away from the machine and someone nefarious attempts to use their session. Let‘s checkout how you can create a custom React hook that wraps a regular npm module called? ? import React from "react"; import ReactDOM from "react-dom"; import createActivityDetector from "activity-detector"; import "./styles.css"; function useIdle(options) { const [isIdle,setIsIdle] = React.useState(false); React.useEffect(() => { const activityDetector = createActivityDetector(options); activityDetector.on("idle",() => setIsIdle(true)); activityDetector.on("active",() => setIsIdle(false)); // clean the subscription return () => { activityDetector.stop(); }; }); return isIdle; } function App() { const isIdle = useIdle({ timeToIdle: 1000 }); return ( <div className="App"> {!isIdle ? <div>Hello World</div> : <div>Are you there?</div>} </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />,rootElement); ? UseEffect (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |