【发布时间】:2016-06-29 22:29:33
【问题描述】:
从传递并呈现给一个组件的帖子数组中,我希望能够将此数组的单个帖子呈现到另一个组件中,但我找不到这样做的方法。
我有两个用于这种情况的组件,第一个组件“博客”呈现数组中所有帖子的预览。每个帖子都有一个<Link to={/blog/post-1/:${post.id}}>Go to post</Link> 到第二个组件“Post”,它从数组中呈现单个帖子。我正在为此使用反应样板。
首先我的容器有一个虚拟的帖子数组:
import React from 'react';
// other imported stuff
import Blog from 'components/Blog';
class BlogPage extends React.Component {
render() {
// dummy posts data
const posts = [
{
id: 1,
title: 'How to Cook Blue Meth',
description: 'Lorem ipsum dolor sit amet, turpis at',
thump: 'thump.jpg',
hero: '/img/',
category: 'k1',
fullname: 'Walter White',
published: '10.05.2016, 15:30pm',
},
{
id: 2,
title: 'Passenger',
description: 'Lorem ipsum dolor sit amet, turpis at',
thump: 'thump.jpg',
hero: '/img/',
category: 'k2',
fullname: 'Chino Moreno',
published: '10.05.2016, 15:30pm',
},
// and more posts...
];
return (
// this is the first component
<div>
<Blog posts={posts} />
</div>
);
}
}
export default connect(null, mapDispatchToProps)(BlogPage);
这是第一个组件博客:
import React from 'react';
import { Link } from 'react-router';
class Blog extends React.Component {
renderPosts() {
return (
<ul>
{this.props.posts.map((post, idx) => {
return (
<li key={idx}>
<p>{post.title}</p>
<p>{post.category}</p>
<p>{post.thump}</p>
<p>{post.fullname}</p>
<p>{post.published}</p>
<Link to={`/blog/post-1/:${post.id}`}>Go to post </Link>
</li>
);
})}
</ul>
);
}
render() {
return (
<div>
{this.renderPosts()}
</div>
);
}
}
Blog.propTypes = {
props: React.PropTypes.array,
};
export default Blog;
还有第二个组件 Post:
import React from 'react';
class Post extends React.Component {
render() {
return (
<div>
<p>{this.props.post.hero}</p>
<p>Title:{this.props.post.title}</p>
<p>{this.props.post.description}</p>
<p>Category:{this.props.post.category}</p>
<p>{this.props.post.thump}</p>
<p>Author:{this.props.post.fullname}</p>
<p>Published:{this.props.post.published}</p>
</div>
);
}
}
Post.propTypes = {
post: React.PropTypes.object,
};
export default Post;
我将第二个组件导入另一个容器:
import React from 'react';
import Post from 'components/Blog/Post';
class PostPage extends React.Component {
render() {
return (
<div>
<Post post={post} />
</div>
);
}
}
export default connect(null, mapDispatchToProps)(PostPage);
这是我的路线:
{
path: '/blog',
name: 'blog',
getComponent(nextState, cb) {
System.import('containers/BlogPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
{
path: '/blog/post-1/:id',
name: 'blog-post-1',
getComponent(nextState, cb) {
System.import('containers/BlogPage/PostPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
我刚刚将此路由添加到 react 样板中的 routes.js。 在这一点上,我不知道如何通过单个帖子进行渲染。任何帮助将不胜感激
【问题讨论】:
-
PostPage的父容器是谁? -
嘿,快速评论:永远不要使用索引作为你的 React 键! React 使用
key属性来确定在删除或添加项目时如何转移事物,并且索引不是唯一的。您需要使用其他东西作为您的key道具。 -
BlogPage 是父级。
-
我真的不明白问题是什么。如果你想渲染一个帖子,
<Post post={post} />不可以吗? -
哦,好吧,你的代码中没有这个。所以你的 BlogPage 是 Blog 和 PostPage 的父级?我认为您也应该显示您的路线配置....因为您可以通过
this.props.params从您的帖子数组中获取当前帖子
标签: javascript arrays reactjs react-router