简体   繁体   English

为什么我无法在React组件中访问Mongo集合?

[英]Why am I unable to access my Mongo collection in a React component?

Using reactjs:react as the official react package isn't installing correctly for Windows yet. 使用reactjs:react作为官方的react软件包尚未针对Windows正确安装。

Just trying to get to grips with React and getting pretty frustrated by what seem to be small things. 只是试图与React保持联系,并对似乎很小的事情感到沮丧。 For some reason I can't actually query any of my Mongo collections via my React components - the basic Mongo queries in the Chrome console work as expected... 由于某些原因,我实际上无法通过我的React组件查询我的任何Mongo集合-Chrome控制台中的基本Mongo查询可以正常工作...

var ExampleComponent = ReactMeteor.createClass({
  getInitialState: function() {
    return {data: []};
  },
  //didn't think the following was necessary, but tried it to no avail:
  startMeteorSubscriptions: function() {
    Meteor.subscribe('exampleCollection');
  },
  componentDidMount: function() {
    var collection = ExampleCollection.find().fetch();
    console.log(collection); //Empty Array []
    console.log(ExampleCollection); //Mongo Collection
    console.log(ExampleCollection.find()); //Cursor
    console.log(ExampleCollection.find().fetch()); //[]?? wtf? 

    this.setState({data: collection});
  },
  render: function() {
    return (
      <div data={this.state.data}>
        Hello World?
      </div>
    );
  }
});

Meteor.startup(function() {
  React.render(<ExampleComponent />, document.getElementById('root'));
})

So what's going on here? 那么这是怎么回事? Any help would be appreciated, I'm not finding as many resources about doing the basics with React and Meteor that I had hoped. 任何帮助将不胜感激,我没有找到我所希望的有关使用React和Meteor进行基础操作的资源。

In reactjs:react, you need to implement a method: getMeteorState() This is what sets your data to be available in your component when render() is called. 在reactjs:react中,您需要实现一个方法: getMeteorState()这是将数据设置为在调用render()时在组件中可用的方法。 You still should implement startMeteorSubscriptions if you're doing pub/sub with your data (which you did correctly). 如果您要对数据进行发布/ startMeteorSubscriptions (正确执行),则仍然应该实现startMeteorSubscriptions

For example: 例如:

var ExampleComponent = ReactMeteor.createClass({
  // Methods specific to ReactMeteor
  startMeteorSubscriptions: function() {
    Meteor.subscribe('exampleCollection');
  },
  getMeteorState: function() {
    return {
      data: ExampleCollection.find().fetch()
    };
  },

  // React Methods
  getInitialState: function() {
    return {};
  },
  render: function() {
    var data = this.state.data;

    return (
      <div>
        {/* Present your data here */}
      </div>
    );
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM