gpt4 book ai didi

reactjs - 使用react的 session 超时警告模式

转载 作者:行者123 更新时间:2023-12-03 13:18:31 26 4
gpt4 key购买 nike

如果用户不采取任何行动,我需要在 13 分钟不活动后显示超时警告模式,并在 15 分钟后结束 session 。我需要使用reactjs 来实现这一点。我在 https://www.npmjs.com/package/react-timeout#react-classic-verbose 检查了 react 超时,但这没有帮助。如果有人知道如何做到这一点,请与我分享。

最佳答案

您可以像这样创建一个高阶组件,并可以通过高阶组件传递子组件

HOC:

`//代码

export default function(ComposedClass) {
class AutoLogout extends React.Component {
constructor(props) {
super(props);
this.state = {
warningTime: 1000 * 60 * 10,
signoutTime: 1000 * 60 * 15,
};
}

componentDidMount() {
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];

for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}

this.setTimeout();
}

clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);

if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};

setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};

resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};

warn = () => {
window.alert("You will be logged out automatically in 1 minute")
console.log('You will be logged out automatically in 1 minute.');
};

logout = () => {
// Send a logout request to the API
console.log('Sending a logout request to the API...');
this.destroy();
};

destroy = () => {
//clear the session
browserHistory.push('/');
window.location.assign('/');
};

render() {

return (
<div>
<ComposedClass {...this.props} />
</div>
);
}
}
}

`

您可以将此 HOC 包装到路由文件中由于不活动而向用户发出警告的所有组件

<Route path="/test" component={HOC(comonent)} />

上面的代码组件将是您要添加此功能的页面。

关于reactjs - 使用react的 session 超时警告模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com