我正在努力弄清楚如何Meteor.user()
在反应组件中等待订阅。我知道用户已登录,因为Meteor.userId()
返回_id
,但尝试访问电子邮件地址显示Meteor.user()
返回未定义。我假设是因为它尚不可用。
唉,因为 Meteor.user() 不是我手动订阅的发布,我不确定如何在 React 组件中等待它。有人可以指点我一个例子吗?
import { Meteor } from 'meteor/meteor';
import React from 'react';
import { Link } from 'react-router';
import { createContainer } from 'meteor/react-meteor-data';
import './BaseLayout.scss';
class BaseLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: (Meteor.userId() !== null) ? true : false,
}
}
componentWillMount() {
if (!this.state.isAuthenticated) {
this.context.router.push('/login');
}
}
componentDidUpdate(prevProps, prevState) {
if (!this.state.isAuthenticated) {
this.context.router.push('/login');
}
}
toggleUserMenu() {
this.refs.userMenu.style.display = (this.refs.userMenu.style.display === 'block') ? 'none' : 'block';
}
logout(e) {
e.preventDefault();
Meteor.logout();
this.context.router.push('/login');
}
render() {
return(
<div id="base">
<div id="header">
<div id="top-bar" className="clear-fix">
<div className="float-left" id="logo"></div>
<div className="float-right" id="user-menu">
<div onClick={this.toggleUserMenu.bind(this)}>
<span>{this.props.currentUser.emails[0].address}</span>
<div className="arrow-down"></div>
</div>
<div id="user-menu-content" ref="userMenu">
<a onClick={this.logout.bind(this)}>Sign Out</a>
</div>
</div>
</div>
</div>
<div id="bodyContainer">
{this.props.children}
</div>
<div id="footer">
<ul>
<li><a href="mailto:test@example.com">Made by Us</a></li>
</ul>
</div>
</div>
)
}
}
BaseLayout.contextTypes = {
router: React.PropTypes.object.isRequired,
}
export default BaseLayoutContainer = createContainer(() => {
var handle = Meteor.subscribe("user.classrooms");
return {
currentUser: Meteor.user(),
dataLoading: !handle.ready(),
classrooms: Classrooms.find({}).fetch(),
};
}, BaseLayout);