我知道有很多问题在讨论这个话题但是,我尝试过的所有问题都会返回一个空数组。我试过了:
这是我的出版物:
Meteor.publish('notes-newest', function () {
return Notes.find().sort({$natural: -1}).limit(10);
});
以下是我尝试访问它的地方:
import { Meteor } from "meteor/meteor";
import React from "react";
import { withRouter } from "react-router-dom";
import { Tracker } from "meteor/tracker";
import { Accounts } from "meteor/accounts-base";
import { Notes } from "../methods/methods";
import SubjectRoutes from "./subjectRoutes/subjectRoutes";
import RenderNotesBySubject from "./renderNotesBySubject";
import Menu from "./Menu.js";
class Home extends React.Component{
constructor(props){
super(props);
this.state = {
notes: []
};
}
componentDidMount() {
Meteor.subscribe('notes-newest')
this.tracker = Tracker.autorun(() => {
const notes = Notes.find().fetch()
if(notes == null || notes == undefined){
return;
}
this.setState({ notes })
})
}
renderNewNotes(){
let notes = this.state.notes;
let count = 10;
console.log(notes);
}
render(){
return (
<div>
<Menu />
<h1></h1>
{this.renderNewNotes()}
</div>
)
}
}
export default withRouter(Home);
新代码
import { Meteor } from "meteor/meteor";
import React from "react";
import { withRouter } from "react-router-dom";
import { Tracker } from "meteor/tracker";
import { Accounts } from "meteor/accounts-base";
import { createContainer } from "meteor/react-meteor-data"
import { Notes } from "../methods/methods";
import SubjectRoutes from "./subjectRoutes/subjectRoutes";
import RenderNotesBySubject from "./renderNotesBySubject";
import Menu from "./Menu.js";
class Home extends React.Component{
constructor(props){
super(props);
this.state = {
notes: []
};
}
componentDidMount() {
// Meteor.subscribe('notes-newest')
this.tracker = Tracker.autorun(() => {
const notes = this.props.list
if(notes == null || notes == undefined){
return;
}
this.setState({ notes })
})
}
renderNewNotes(){
let notes = this.state.notes;
let count = 10;
console.log(notes);
}
render(){
return (
<div>
<Menu />
<h1></h1>
{this.renderNewNotes()}
</div>
)
}
}
export default createContainer(({props})=>{
Meteor.subscribe("notes-newest", props);
return{
list: Notes.find().fetch(),
}
}, Home);
答案 0 :(得分:1)
您的publication
似乎没问题。您所需要的只是使用数据容器。我建议使用react-meteor-data在meteot中使用反应数据加载。
创建一个更高阶的类来包装你的数据并将你现有的组件保留为表示组件,它将呈现数据容器提供的数据。
希望以下片段有助于:
export default createContainer(({props})=>{
Meteor.subscribe("data.fetch", props);
return{
list: CollectionName.find().fetch(),
}
}, PresentationComponent);
说明:createComponent将确保数据的反应性,并将检索到的数据作为PresentationComponent
发送到props
。
答案 1 :(得分:0)
您正在将mongodb原生语法与Meteor mongo语法混合使用。你需要:
Meteor.publish('notes-newest', function () {
return Notes.find({},{sort: {$natural: -1}, limit: 10});
});
并且在客户端同上:
list: Notes.find({},{sort: {$natural: -1}, limit: 10});