[英]How to get Accounts.onLogin to impact my app in Meteor React ES6?
我希望流星應用程序在登錄和注銷時在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
您應該使用Meteor的內置反應性數據源來確定用戶的登錄狀態:
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);
現在,Meteor將this.props.isLoggedIn
為您動態更新this.props.isLoggedIn
。 請注意,您需要安裝meteor/react-meteor-data
並導入createContainer
才能起作用:
import { createContainer } from 'meteor/react-meteor-data';
如果您在用戶登錄時仍需要執行某些操作,則可以將Accounts.onLogin
基本上放置在應用程序中的任何位置,只要考慮要運行服務器端還是客戶端,或者同時運行它們即可。 有關應用程序結構的最佳做法,請參閱《流星指南》 。
事實證明,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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.