[英]Session timer in ReactJS
I need to organize notification which will tell user, that his session will be end after some minutes. 我需要组织通知,该通知将告诉用户他的会话将在几分钟后结束。 For this after page load I get total session time, and parameter which tells me when I must show notification(for example 1000secs-session time and 60-time which remains till session is end) from api.
对于此页面加载后,我获得了总会话时间,以及参数,该参数告诉我何时必须从api显示通知(例如1000secs会话时间和60倍的时间,直到会话结束为止)。 How I understand I need to organize a timer with setTimeout method.
我的理解我需要使用setTimeout方法来组织计时器。 But I can't realize how to organize this mechanism acording to react philosophy.
但是我不知道如何根据反应哲学来组织这种机制。 How can it be performed?
如何执行?
In your root component set a timeout and show a notification. 在您的根组件中设置一个超时并显示一条通知。 I dont know how you get the session time, but lets assume that the session time is just available.
我不知道您如何获得会话时间,但让我们假设会话时间才可用。 Then you can do something like this (using ES6):
然后,您可以执行以下操作(使用ES6):
const React = require('react');
const PropTypes = require('prop-types');
export class Main extends React.Component
{
constructor(props)
{
super(props);
this.state = {
timerid: -1,
sessionEndsSoon: false,
};
this.getSessionTimeout = this.getSessionTimeout.bind(this);
}
componentDidMount()
{
this.setState({ timerid: this.getSessionTimeout() });
}
componentWillUnmount()
{
clearTimeout(this.state.timerid);
}
getSessionTimeout()
{
if (this.state.timerid)
{
clearTimeout(this.state.timerid);
}
timerid = setTimeout(() =>
{
this.setState({sessionEndsSoon : true});
}, this.props.sessionTimeInMs);
return timerid;
}
render()
{
if(this.state.sessionEndsSoon)
{
return (<p>Session ends soon</p>);
}
return (<p>session active</p>);
}
}
Main.propTypes = {
sessionTimeInMs: PropTypes.number.isRequired,
};
Main.defaultProps =
{
sessionTimeInMs: 1000000,
};
Futhermore you can get the session time from the backend via ajax and update the timeout accordingly. 此外,您可以通过ajax从后端获取会话时间,并相应地更新超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.