简体   繁体   中英

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.

Just trying to get to grips with React and getting pretty frustrated by what seem to be small things. 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...

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.

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. You still should implement startMeteorSubscriptions if you're doing pub/sub with your data (which you did correctly).

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>
    );
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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