我想用Meteor和React显示我的文章组件,但我的Post.findOne()返回undefined,我不明白为什么:
class Article extends Component {
render() {
console.log(this.props);
return (
this.props.loading
? <span>Loading...</span>
: <h1>{this.props.match.params.slug}</h1>
);
}
}
Article.propTypes = {
post: React.PropTypes.object,
loading: React.PropTypes.bool
}
ArticleContainer = createContainer(({ slug }) => {
const postHandle = Meteor.subscribe('post');
const post = Post.findOne({
'slug': "super-test"
});
const loading = !postHandle.ready();
return {
loading,
post
};
}, Article);
export default ArticleContainer;
发布方式:
Meteor.publish('post', () => {
return Post.find();
});
console.log返回:
Object { match: Object, location: Object, history: Object, staticContext: undefined, loading: true, post: undefined } app.js:392:7
Object { match: Object, location: Object, history: Object, staticContext: undefined, loading: true, post: Object } app.js:392:7
我的路线:
<AppLayout path='/blog/:slug' component={ArticleContainer} />
任何人都可以帮我解决这个问题吗?
谢谢社区!
答案 0 :(得分:0)
它是undefined
,因为订阅是异步的。即使未提取post
,您的组件也会呈现。您应该使用已定义的loading
属性:
class Article extends Component {
render() {
return (
loading
? <span>Loading...</span>
: <h1>{this.props.match.params.slug}</h1>
);
}
}