【发布时间】:2019-10-17 09:43:27
【问题描述】:
我正在尝试使用 React 空闲计时器在 15 分钟后进入锁定屏幕。
我遇到的问题是重定向页面。我将电子与反应和反应浏览器路由器一起使用。因此我不能使用 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
【问题讨论】:
-
既然路由现在只是组件,那么将空闲超时行为移动到包装路由的新组件中是否有意义?然后你就可以像往常一样使用 history.push 了。
-
可以使用withRouter:reacttraining.com/react-router/web/api/withRouter
-
IdleTimer 不允许你传递孩子吗?您可以将 BrowserRouter 中的 div 替换为 IdleTimer,然后将开关放在里面。
-
history.push 在其他组件中继续正常工作。我需要它在渲染区域上方的 onIdle 操作方法中工作。
标签: javascript reactjs electron