大家。
几天来一直有一个我似乎无法解决的问题。
在我的Redux应用程序中,我将有三个不同的组件PostComponent
PostDetails
Posts
在PostComponent
中正在构建一个帖子(构建单个帖子的UI)。这个UI的一部分我需要有一些“评论”(评论:2等)我的reducer是以一种在每个主帖的键下返回注释的分组对象的方式构建的。
我的Redux商店的状态在mapStateToProps
内为PostComponent
但是目前我在路由undefined
的{{1}}收到/
当我进入详细视图时comments
我的/:category/:postId
正在返回ownProps.postId
如果有人知道为什么会这样,我真的很感激!
回购: https://github.com/petterostergren/readable_udacity
评论缩减器undefined
state = {}
帖子(case COMMENTS_GET_COMMENTS:
return {
...state,
comments: _.groupBy(action.payload, 'parentId'),
}
)
/
PostDetailes(class Posts extends Component {
componentDidMount() {
const { getPosts } = this.props
getPosts()
}
renderPosts() {
const { posts } = this.props
return _.map(posts, post => {
return (
<div>
<PostComponent
key={post.id}
postId={post.id}
title={post.title}
body={false}
readirect
author={post.author}
voteScore={post.voteScore}
category={post.category}
timestamp={post.timestamp}
/>
</div>
)
})
}
render() {
return <div>{this.renderPosts()}</div>
}
}
export default connect(
state => ({
posts: _.filter(state.posts, ['deleted', false]),
}),
{
getPosts,
}
)(Posts)
)
/:category/:postID
PostComponent(正在注入的那个)
class PostDetails extends Component {
componentDidMount() {
const { getPosts, getComments, match } = this.props
getPost(match.params.postId)
getComments(match.params.postId)
}
renderComments() {
const { comments, posts, match } = this.props
return _.map(comments, comment => {
return (
<PostComponent
key={comment.id}
postId={comment.id}
isPost={false}
title=""
body={comment.body}
readirect={false}
author={comment.author}
voteScore={comment.voteScore}
category=""
timestamp={comment.timestamp}
/>
)
})
}
renderPosts() {
const { posts } = this.props
return (
<PostComponent
key={posts.id}
postId={posts.id}
title={posts.title}
body={posts.body}
readirect={false}
author={posts.author}
voteScore={posts.voteScore}
category={posts.category}
timestamp={posts.timestamp}
/>
)
}
render() {
return (
<div>
{this.renderPosts()} <hr /> {this.renderComments()}
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
console.log("PostDetails, mapStateToProps ownProps ")
console.log(ownProps)
return {
comments: state.comments[ownProps.match.params.postId],
posts: _.filter(state.posts, ['deleted', false]),
}
}
export default connect(mapStateToProps, { getPost, getComments })(PostDetails)
答案 0 :(得分:0)
大家好,我最后改变了一些事情让它发挥作用
建立我的减速机如下:
import { COMMENTS_GET_COMMENTS } from '../actions/actionConstants'
const comments = (state = {}, action) => {
switch (action.type) {
case COMMENTS_GET_COMMENTS:
return {
...state,
[action.meta]: action.payload,
}
default:
return state
}
}
export default comments
然后在我的组件中调用它
const mapStateToProps = (state, ownProps) => {
return {
comments: state.comments[ownProps.postId]
? state.comments[ownProps.postId]
: [],
}
}
这使我有可能在我的UI
中将其用作{this.props.comments.length}