如何使用React从客户端检索Meteor集合中的数据?

时间:2017-04-02 06:04:24

标签: javascript reactjs meteor

我尝试使用下面的代码检索集合的服务器数据,但它只返回undefined。



import { Posts } from '../../../api/posts.js';

class FeedUnit extends Component {

  constructor(props) {
      super(props);

      this.state = {
          open: true,
          emojis: false,
          isOver: false,
          likes: this.setLike(),
      };
  }
  
    setLike(){
    let self = this;
    let like;

    let post = Posts.findOne({ external_id: this.props.data.id });
    console.log(Posts.findOne({}))
    return like;
  }
  




我已经手动搜索了数据库,并且使用以下命令获得了正确的返回:



db.posts.findOne({external_id: '1402366059774445_1503319816345735'})




3 个答案:

答案 0 :(得分:1)

我在@mostafiz rahman的评论中找到了解决方案,我应该放publishsubscribe,如下所示:



if (Meteor.isServer) {
  // This code only runs on the server
  // This is necessary to reatrieve data on the client side
  Meteor.publish('posts', function tasksPublication() {
    return Posts.find();
  });
}






  componentDidMount() {
    Meteor.subscribe('posts');
  }




答案 1 :(得分:1)

我认为这是使用Meteor / react的一些连接器的最佳解决方案。我更喜欢react-komposer

U必须创建允许对Meteor集合中的变化进行反应的函数:

function getTrackerLoader(reactiveMapper) {
  return (props, onData, env) => {
    let trackerCleanup = null;
    const handler = Tracker.nonreactive(() => {
      return Tracker.autorun(() => {
        // assign the custom clean-up function.
        trackerCleanup = reactiveMapper(props, onData, env);
      });
    });

    return () => {
      if(typeof trackerCleanup === 'function') trackerCleanup();
      return handler.stop();
    };
  };
}

在那个换行组件之后:

    import { Posts } from '../../../api/posts.js';

        class FeedUnit extends Component {

          constructor(props) {
              super(props);

              this.state = {
                  open: true,
                  emojis: false,
                  isOver: false,
                  likes: this.setLike(),
              };
          }

            setLike(){
              let self = this;
              let like;

              let post = this.props.post
              console.log(post)
              return like;
          }
}
function reactiveMapper(props, onData) {
    if (Meteor.subscribe('posts').ready()) {
        let post = Posts.findOne({ external_id: props.data.id });
        onData(null, { post });
    }
}

export default compose(getTrackerLoader(reactiveMapper))(FeedUnit);

有关详细信息,请查看docs

答案 2 :(得分:0)

Posts.findOne is async function you need either to get data from callback or by promise as below 
 Posts.findOne({ external_id: this.props.data.id })
.then((posts)=>{
//do whatever you want
})
.catch(err=>console.log(err))