我正在使用React + Redux,我想创建一个点赞计数器,但是出现错误“无法读取未定义的属性” map”。
我的减速器代码:
const initialState = {
comments: [],
text: ''
}
case PUT_LIKE: {
return {
...state,
comments: state.comments.id === action.id ? state.comments.like + 1 : state.comments.like
}
}
//before this I have this case for posting comments
case ADD_COMMENT: {
let newComment = {
id: shortid.generate(),
text: state.text,
like: 0,
dislike: 0,
rating: 0
}
return {
...state,
comments: [newComment, ...state.comments],
text: ''
}
}
我的组件的代码(为了简化起见,删除了一些代码):
const ClientFeedback = ({comments,text,postComment,onCommentChange,putLike}) => {
return (
<div className='comments-container'>
{comments.map(m =>
<div key={m.id} className='comment-container'>
<div className='name'>
{nameImg}John
<span className='product-rating'>{rating}{rating}{rating}</span>
<SetDate />
</div>
<div className='text-comment'>
<span onClick={putLike} className='like'>{like}{m.like}</span>
<span className='dislike'>{dislike}{m.dislike}</span>
<div className='text'>{m.text}</div>
</div>
</div>)}
</div>
)
}
容器
class FeedbackContainer extends React.Component {
render() {
return (
<ClientFeedback {...this.props}/>
)
}
}
const mapStateToProps = (state) => ({
comments: state.feedbackReducer.comments,
text: state.feedbackReducer.text
})
export default compose(connect(mapStateToProps,{postComment,onCommentChange,putLike})(FeedbackContainer))
操作代码:
export const putLike = (id) => ({type: 'PUT_LIKE', id})
很抱歉,但这很烦人: ( 看起来您的帖子大部分是代码;请添加更多详细信息
您的帖子似乎主要是代码;请添加更多详细信息)
答案 0 :(得分:1)
您的减速器应执行以下操作:
case PUT_LIKE: {
return {
...state,
comments: state.comments.map(comment=>comment.id === action.id ? {...comment, like: comment.like+1} : comment)
}
}
答案 1 :(得分:0)
问题是您对PUT_LIKE操作设置的注释不正确。您需要映射评论,并设置更新值等特定评论
case PUT_LIKE: {
return {
...state,
comments: state.comments.map(comments => comments.id === action.id ?
({...comments, like: comments.like + 1}) : comments)
}
}
答案 2 :(得分:0)
我认为此代码段会导致错误。
case PUT_LIKE: {
return {
...state,
comments: state.comments.id === action.id ? state.comments.like + 1 : state.comments.like
}
}
您应该尝试:
case PUT_LIKE: {
return {
...state,
comments: state.comments.map(comment => {
if(comment.id === action.id) return {...comment, like: comment.like + 1}
return comment
})
}
}