[英]Using React with Meteor: how to handle Meteor.user() after logging out
我的Meteor應用程序中有一個使用React組件構建的用戶配置文件頁面。 因為它使用Meteor.user()來創建其中一個變量,所以每當我退出應用程序時都會收到錯誤(但前提是我之前訪問過當前會話中的配置文件頁面)。 它確實對我有意義,因為沒有當前用戶,Meteor.user()不再可用,因此它將錯誤地顯示“無法讀取'支持'未定義”消息。
AccountList = React.createClass({
mixins: [ReactMeteorData],
getMeteorData(){
var user;
var supportingUserId = Meteor.user().support.supportingUserId;
supportingUserId ? user = Meteor.users.findOne({_id: supportingUserId}) : user = Meteor.user();
return {
accounts: Accounts.find({owner: user._id}).fetch()
}
}...
最初,我嘗試更改上面的代碼塊,將違規代碼包裝在if語句中,如下所示:
AccountList = React.createClass({
mixins: [ReactMeteorData],
getMeteorData(){
var user;
if (Meteor.user()){
var supportingUserId = Meteor.user().support.supportingUserId;
supportingUserId ? user = Meteor.users.findOne({_id: supportingUserId}) : user = Meteor.user();
return {
accounts: Accounts.find({owner: user._id}).fetch()
}
}
else{
return {};
}
}...
但是我遇到了另一個錯誤:“無法讀取未定義的屬性'長度',這是由未定義的帳戶引起的(從另一個需要'帳戶'進一步向下的渲染方法觸發)。 我最終采用相同的方法並添加了額外的if語句,但遇到了另一個類似的錯誤。 我的問題是,是否可以解決這個問題,而無需將一半的應用程序包裝在“if(Meteor.user())”語句中。 或者,如果有可能在注銷時清除應用程序以記住加載的React組件?
嘗試
return {accounts: []};
代替
return {};
並且永遠不要假設, accounts.length > 0
。
米歇爾弗洛伊德的方式是正確的!
您可以在路由器中執行以下操作:
FlowRouter.route('/profile/edit', {
name: 'profile.edit',
triggersEnter: [function(context, redirect) {
if(!Meteor.user()){
console.log('User not logged in. Redirecting...');
redirect('login');
}
}],
action(params) {
mount(FullLayout, {
content: <ProfileEditComposer />
});
}
});
(我在我的Meteor / React應用程序中使用FlowRouter,如果你使用其他類型的路由器,代碼會有點不同,但是,我認為應該是相同的想法)
上面的代碼行阻止未登錄的用戶編輯配置文件頁面並將其重定向到登錄頁面。 通過這種方式,您無需在Profile-Edit組件或所有其他組件中更改代碼,當這些組件嘗試通過用戶對象訪問和循環值時可能會產生大量錯誤 - 在這種情況下未定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.