我的 Meteor 应用程序中有一个使用 React 组件构建的用户个人资料页面。因为它使用 Meteor.user() 创建变量之一,所以每当我注销应用程序时都会收到错误消息(但前提是我之前曾在当前 session 中访问过个人资料页面)。这对我来说确实有意义,因为没有当前用户,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
。
关于javascript - 注销后使用 React with Meteor : how to handle Meteor. user(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35048907/