我无法访问对象的属性

I can't access an object's properties

接下来的几行工作正常,我可以在控制台日志中看到整个对象:

Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject)

在控制台中,我可以看到 oneProject 的属性,甚至 name 属性。

现在用下面几行,结果是错误的:

Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject.name)

错误是:"Cannot read property 'name' of undefined"。

这是完整的代码:

import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Projects } from '/imports/api/projects.js';
import ProjectFormUpdate from './ProjectFormUpdate.jsx';

export default ProjectFormUpdateContainer = withTracker(({ key1 }) => {
  Meteor.subscribe('projects')
  var oneProject = Projects.findOne(key1);
  console.log(oneProject.name)
  return {
    oneProject:oneProject,
  };
})(ProjectFormUpdate);

Meteor 中的订阅是异步。这意味着数据并不总是立即可用。

Tracker.autorun(() => {
  const sub = Meteor.subscribe('projects');
  if (sub.ready()){
    const oneProject = Projects.findOne(key1);
    console.log(oneProject.name);
  }
});

在订阅准备就绪之前不会尝试查找项目。