我希望流星应用程序在登录和注销时在App中调用setState。我如何让一段代码(即Accounts.onLogon)影响另一个组件(例如App {})的内部?另外,如何检测注销?
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查看React中什么时候发生了变化,如下所示:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句