我正在尝试在我的 Meteor 应用程序中将meteor-useraccounts包与React集成。我已经走了很远,但正在努力实现一个history.push()
或等效的回调函数AccountsTemplate.logout()
- 后者是注销用户的内置方式。
回调函数的配置是这样完成的:
AccountsTemplates.configure({
onLogoutHook: myLogoutFunc
})
但我不能在 React.Component 的“类”中做到这一点。所以我需要定义使用浏览器历史记录的回调函数,但我猜它不在任何组件范围内。
对于点击登录/退出 按钮的情况,我找到了如下解决方案:
class LogInOutButton extends Component {
constructor(props) {
super(props);
this.state = {
loggedIn: Meteor.userId() ? true : false,
redirect: false
}
this.redirectToSignIn = this.redirectToSignIn.bind(this);
window.logInOutButton = this;
}
redirectToSignIn() {
if (!this.state.loggedIn && document.location.pathname !== "/signIn")
this.setState({redirect: <Redirect to="/signIn" />});
}
render() {
const { redirect } = this.state
return (
<li className="nav-item">
{redirect}
<a className="nav-link" href="#"
onClick={Meteor.userId() ? AccountsTemplates.logout : this.redirectToSignIn}>
{Meteor.userId() ? "Sign Out" : "Sign In"}
</a>
</li>
)
}
}
如您所见,例如,我尝试redirectToSignIn()
通过使其成为全局窗口对象的成员来从外部调用该方法。感觉不对,也不起作用:
var myLogoutFunc = () =>
window.logInOutButton.redirectToSignIn();
我还尝试了以下方法:
var myLogoutFunc = withRouter(({history}) =>
<div onLoad={history.push="/signIn"}>
</div>
)
但是,这行不通,因为withRouter
需要一个组件作为参数,如果我做对了吗?至少这是我试图解释以下错误的方式:
Exception in delivering result of invoking 'logout': TypeError: "props is undefined"
在withRouter
模块中阅读此内容后:
var withRouter = function withRouter(Component) {
var C = function C(props) {
...
你会如何解决这个问题?