我正在尝试使用React Idle Timer在15分钟后进入锁定屏幕。
我遇到的问题是重定向页面。我正在使用带有react和react BrowserRouter的电子。因此,我不能使用window.location.assign('/ clock'); (或类似的window.location)方法来重定向页面。通常在我的组件中使用:
this.props.history.push("/clock");
这在BrowserRouter的Switch内的组件中起作用。但是,我需要React Idle Timer处于最高级别,并且当我在 onIdle 函数中使用props.history.push时,会收到以下消息:
Uncaught TypeError: Cannot read property 'push' of undefined
class AppRouter extends Component {
constructor(props) {
super(props);
this.idleTimer = null;
this.onAction = this._onAction.bind(this);
this.onActive = this._onActive.bind(this);
this.onIdle = this._onIdle.bind(this);
}
_onAction(e) {
console.log("user did something", e);
}
_onActive(e) {
console.log("user is active", e);
console.log("time remaining", this.idleTimer.getRemainingTime());
}
_onIdle(e) {
console.log("user is idle", e);
console.log("last active", this.idleTimer.getLastActiveTime());
//need to push to /clock after 15 minutes
//window.location.assign('/clock'); -- WORKS in browser, but not with Electron
// this.props.history.push("/clock"); -- gives Uncaught TypeError: Cannot read property 'push' of undefined
//can't place <IdleTimer inside BrowserRouter because it only allows 1 thing within.
}
render() {
return (
<div>
<IdleTimer
ref={ref => {
this.idleTimer = ref;
}}
element={document}
onActive={this.onActive}
onIdle={this.onIdle}
onAction={this.onAction}
debounce={250}
timeout={1000 * 60 * 0.1}
/>
<BrowserRouter>
<div>
<Switch>
<Route path="/institution" component={Institution} />
<Route path="/location" component={Location} />
<Route path="/timezone" component={TimeZone} />
<Route path="/clock" component={Clock} />
<Route path="/" component={PreflightCheck} />
</Switch>
</div>
</BrowserRouter>
</div>
);
}
}
ReactDOM.render(<AppRouter />, document.getElementById("root"));
重定向到BrowserRouter标记之外的顶层组件的正确方法是什么?
我也尝试过这个:
import { createHashHistory } from 'history'
export const history = createHashHistory()
然后调用history.push('/ clock');
这似乎只是将/ clock附加到我当前所在的页面上,并显示以下消息:
Hash history cannot PUSH the same path; a new entry will not be added to the history stack
答案 0 :(得分:0)
创建历史记录(您可以使用npm安装历史记录):
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
然后将空闲计时器放在路由器中。在这种情况下,BrowserRouter似乎无法与Router一起使用。
<Router history={history}>
<div>
<IdleTimer
ref={ref => {
this.idleTimer = ref;
}}
element={document}
onActive={this.onActive}
onIdle={() => this.checkplayerstatus(history)}
onAction={this.onAction}
debounce={250}
timeout={1000 * 60 * 15}
/>
<Switch>
<Route path="/institution" component={Institution} />
<Route path="/location" component={Location} />
<Route path="/timezone" component={TimeZone} />
<Route path="/clock" component={Clock} />
<Route path="/" component={PreflightCheck} />
</Switch>
</div>
</>
然后在onIdle函数中可以执行以下操作:“ whatevervariableyoupassashistoryfromonidle” .push(“ / clock”)。