【问题标题】:Why am I unable to access my Mongo collection in a React component?为什么我无法在 React 组件中访问我的 Mongo 集合?
【发布时间】:2015-09-22 10:22:19
【问题描述】:

使用 reactjs:react 作为官方的 react 包尚未正确安装 Windows。

只是试图掌握 React 并且对看似很小的事情感到非常沮丧。由于某种原因,我实际上无法通过我的 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'));
})

那么这里发生了什么?任何帮助将不胜感激,我没有找到我希望的关于使用 React 和 Meteor 做基础知识的资源。

【问题讨论】:

  • 您期望发生什么? setState 只会导致重新渲染,但由于 state.data 不会影响显示的内容,我认为显示不会改变?
  • fetchfind 都是异步的。因此,当您调用 setState 时没有结果。

标签: javascript mongodb meteor reactjs


【解决方案1】:

在reactjs:react中,需要实现一个方法:getMeteorState() 这就是在调用 render() 时设置您的数据在组件中可用的原因。如果您正在使用您的数据进行发布/订阅(您做得正确),您仍然应该实现 startMeteorSubscriptions

例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2021-11-19
    • 1970-01-01
    • 2015-04-23
    相关资源
    最近更新 更多