如何让Accounts.onLogin在Meteor React ES6中影响我的应用程序?
问题描述:
我希望我的流星应用在登录和注销时调用App中的setState。我如何让一段代码(即:Accounts.onLogon)影响另一个组件(即App {})?另外,如何检测退出?如何让Accounts.onLogin在Meteor React ES6中影响我的应用程序?
Accounts.onLogin(function(user){
console.log('hi');
//App.showPrivate();
});
class App extends Component {
constructor(props) {
super(props);
this.state = {
showPublic: false,
};
}
toggleShowPublic() {
this.setState({
showPublic: !this.state.showPublic,
});
}
showPublic() {
this.setState({
showPublic: true,
});
}
showPrivate() {
this.setState({
showPublic: false,
});
}
render() {
return (
<div className="container">
<div className="show-public" onClick={this.toggleShowPublic.bind(this)}>
{this.state.showPublic ?
<span className="private-public"> View private</span> :
<span className="private-public"> View public </span>
}
</div>
</div>
);
}
}
答
原来Accounts.onLogin是一个分心。要在用户登录或注销时更新应用程序,我们需要查看登录用户更改的时间并做出相应的反应。当有些变化的反应眼看使用componentWillReceiveProps完成,如图所示:
componentWillReceiveProps(nextProps) {
// user just logged in/out
if (!this.props.currentUser && nextProps.currentUser) {
this.setState({ showPublic: false });
}
}
哦,和目前的用户来自:
export default createContainer(() => {
return {
currentUser: Meteor.user(),
};
}, App);
答
而不是Accounts.onLogin
你应该使用流星的内置反应的数据源,以确定用户的登录状态:
class App extends Component {
constructor(props) {
super(props);
this.state = { showPublic: false };
}
toggleShowPublic() {
this.setState({ showPublic: !this.state.showPublic });
}
render() {
return (
<div className="container">
{this.props.isLoggedIn ?
<div className="show-public" onClick={this.toggleShowPublic.bind(this)}>
{showPrivate ?
<span className="private-public"> View private</span> :
<span className="private-public"> View public </span>
}
</div> :
Show something else if the user is not logged in here...
}
</div>
);
}
}
export default createContainer(() => {
return {
isLoggedIn: !!Meteor.user()
}
}, App);
现在流星将采取被动地更新this.props.isLoggedIn
为您服务。请注意,您需要安装meteor/react-meteor-data
并导入createContainer
这个工作:
import { createContainer } from 'meteor/react-meteor-data';
如果您仍然需要做一些事情,当用户登录时,你可以把Accounts.onLogin
基本上任何你想要在你的应用程序,只要你考虑你是想让它运行服务器端还是客户端,还是两者兼而有之。有关应用程序结构的最佳实践,请查看Meteor Guide。
感谢您的答复,但我是问如何使show_public在用户登录时设置为false,理想情况下在用户注销时也将其设置为true。 –
侧面的问题:是否有任何this.props.isLoggedIn和this.props.currentUser之间的显着差异? –
所以重新迭代,我如何获得Accounts.onLogin影响我的应用程序组件内的东西? –