【发布时间】:2017-12-30 22:23:42
【问题描述】:
我正在创建一个包含三篇文章的博客,最初显示为三张卡片,用户可以单击它们以呈现与卡片匹配的文章组件。现在,我正在使用减速器来提取每个帖子卡片中使用的必要细节。
这是我的问题:我正在使用三个单独的帖子组件(Post1、Post2 和 Post3),它们充当每个 Route 标记中使用的组件。但是,我想让我的代码更加动态,并且能够在每个 Route 标记中呈现一个通用的 post 组件,并以某种方式使用来自特定 reducers 对象的信息填充 post 组件,该对象已经用于提取信息以在每张卡中使用.
所以,我希望能够写出这样的东西:
<Route exact exact path={`Post1`} component={Post}/>
然后,当点击相应的卡片时,该特定的 Post 实例将以某种方式呈现 Post,其中包含来自专门用于 Post1 的 reducer 对象的道具。
有什么办法可以做到吗???
这是我的 App.js 代码:
class App extends React.Component {
render() {
const blogPosts = {
Post1,
Post2,
Post3
};
var createRoutes = this.props.cards.map((card, i) => {
return <Route key={i} exact path={`/${card.title}`} exact component={blogPosts[card.id]}/>
});
return(
<Switch>
<Route exact path='/' component={PostCards}/>
{createRoutes}
</Switch>
);
}
}
function mapStateToProps(state) {
return {
cards: state.cards
}
}
export default withRouter(connect(mapStateToProps)(App));
这是我的卡片列表代码:
class PostCards extends React.Component {
render() {
var createCards = this.props.cards.map((card, i) => {
return (
<div style={{margin: '20px'}} key={i}>
<Link to={`/${card.title}`}>
<PostCard title={card.title} subtitle={card.subtitle} date={card.date} text={card.text} backgroundImage={card.image} detail={card.detail}/>
</Link>
</div>
);
});
return (
<div style={{display: 'flex', flexDirection: 'row'}}>{createCards}</div>
);
};
}
function mapStateToProps(state) {
return {
cards: state.cards
};
}
export default connect(mapStateToProps)(PostCards);
帖子 (Post1) 的代码示例:
const Post1 = () => {
return (
<div>hello this is post 1</div>
);
}
export default Post1;
以及reducer的代码:
export default function() {
return [
{ id: 'Post1',
title: 'Post1',
subtitle: 'subtitle',
date: '1.1.17',
text: 'this is the post text for post 1',
image: 'url("../client/images/image.jpg")',
detail: 'this is the detail'
},
{ id: 'Post2',
title: 'Post2',
subtitle: 'subtitle',
date: '2.1.17',
text: 'this is the post text for post 2',
image: 'url("../client/images/image.jpg")',
detail: 'this is the detail'
},
{ id: 'Post3',
title: 'Post3',
subtitle: 'subtitle',
date: '3.1.17',
text: 'this is the post text for post 3',
image: 'url("../client/images/image.jpg")',
detail: 'this is the detail'
},
]
}
【问题讨论】:
标签: javascript reactjs react-router react-redux react-router-dom