对于 React 和 ES6 约定来说非常新。我正在尝试从 componentWillMount()
内部的函数内调用操作。这会导致未捕获类型错误:无法读取未定义的属性“signoutUser”
。不太确定如何解决它,尝试绑定(bind) this
,这确实解决了问题。
这是我当前形式的代码:
// left_site.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { signoutUser } from '../actions/authentication';
export default function(ComposedComponent) {
class LeftSite extends Component {
constructor(props, context) {
super(props, context);
}
componentWillMount() {
var timerLeft = setInterval(timer, 1000);
function timer() {
if ((sessionStorage.getItem('timer') > 0) &&
(new Date().getTime() - sessionStorage.getItem('timer') > 5000)) {
this.props.signoutUser();
} else {
sessionStorage.setItem('timer', new Date().getTime());
}
}
}
render() {
return <ComposedComponent {...this.props} />
}
}
return connect( null, { signoutUser })(LeftSite);
}
为了解释发生的情况,该公司希望用户在从域上的任何 protected 路由导航到另一个域时自动注销。一个想法是创建一个“心跳”,只要用户位于域中 protected 路由上,每秒都会将时间提交给 sessionStorage
。这个想法是,如果导航到另一个域,然后尝试返回,如果上次存储的时间与当前时间的差值大于 5000ms,则会自动注销。
可能有更好的方法来做到这一点,但我想不出一种 1) 不会侵犯隐私或 2) 不会通过刷新、取消绑定(bind)
触发注销的方法例如。
left_site.js
是一个 HOC - 我还有一个 required_login.js
HOC,如果有人尝试在未经身份验证的情况下访问 protected 路由,则可以重新路由到登录页面--所以我的 protected 路由被包装在 component={LeftSite(RequireAuth(Home))}
中。
LeftSite
运行正常,但是当条件计算为 true
并尝试触发 this.props.signoutUser();
出现错误。
最佳答案
函数timer
未绑定(bind)到类。当它定期执行时,执行上下文会发生变化。使用前必须先绑定(bind)该函数。还要确保在适当的时间或在卸载组件时清除间隔。我建议你这样写
timer = () => {
if ((sessionStorage.getItem('timer') > 0) &&
(new Date().getTime() - sessionStorage.getItem('timer') > 5000)) {
this.props.signoutUser();
} else {
sessionStorage.setItem('timer', new Date().getTime());
}
}
componentWillMount() {
this.timerLeft = setInterval(this.timer, 1000)
}
componentWillUnmount() {
clearInterval(this.timerLeft);
}
关于javascript - 在 componentWillMount 内的函数内调用操作导致无法读取未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46121462/