繁体   English   中英

反应Redux动作和Reducer映射错误

[英]React Redux actions and reducer mapping error

我对使用Redux还是很陌生,我试图将我的动作和reducer正确地绑定到另一个组件时遇到了问题。 因此,我只是尝试一些简单的操作,例如在帖子中添加评论。 用户键入他们的名字,然后输入他们的评论,我希望两者都显示。 我试图找到在我的减速器中编写此代码的最佳方法。

这是我的行动

export const ADD_COMMENT = 'ADD_COMMENT';
export const addComment = (author, comment) => ({
 type: ADD_COMMENT,
  author,
  comment
});

这是我的comment.js

import React from 'react';
import {connect} from 'react-redux';
import CommentForm from './comment-form';

export function Comments(props) {
 const comments = props.comments.map((comment, index) => (
    <li key={index}>
        <div className="author">{comment.author} says:</div>
        <div className="comment">{comment.comment}</div>
    </li>
));
return (
    <section>
        <h2>Comments</h2>
        {comments.length ? <ul>{comments}</ul> : <div>No comments</div>}
        <h3>Add a comment</h3>
        <CommentForm />
    </section>
);
}

export const mapStateToProps = (state, props) => ({
comments: state.comments
});

export default connect(mapStateToProps)(Comments);

这是我的reducer.js

import {ADD_COMMENT} from './actions';

const initialState = {
 comments: []
};

export default function(state = initialState, action){
 if(action.type === ADD_COMMENT){
    return Object.assign({}, state, {
        comments: action.comments
    });
}

return state;
}

我现在有这种方式,我在我的reducer的函数中得到了一个“无法读取未定义的属性映射。我尝试将author:添加到我的初始状态和author:action.author中,并且仍然是同一件事。所以我我知道我的问题与我如何编写减速器有关。

以下解决方案将帮助您从reducer获取注释并将其呈现在组件中(如果您有可用注释),否则将不显示no comments

该解决方案通过对Comments.js,操作和Reducer中进行的所有更正解决了以下问题

无法读取未定义的属性映射

尝试添加注释id作为li元素而不是索引的键。 当您没有数据的唯一ID时,索引始终应该是第二选择

更新:

您在减速器中遇到错字错误,需要调用action.comment,但您正在调用action.comments。 检查下面的更正

import {ADD_COMMENT} from './actions';
const initialState = {
 comments: []
};

export default function(state = initialState, action){
  if(action.type === ADD_COMMENT){
    state.comments = action.comment;
    return state;
  }else{
     return state;
  }
}

更正的comments.js代码

import React from 'react';
import {connect} from 'react-redux';
import CommentForm from './comment-form';

export function Comments(props) {
return (
    <section>
        <h2>Comments</h2>
         <ul>
        {Array.isArray(props.comments) && props.comments.length > 0 && props.comments.map((comment, index) => (
      <li key={index}>
         <div className="author">{comment.author} says:              </div>
          <div className="comment">{comment.comment}</div>
        </li>
   ))}
    </ul>

    {!Array.isArray(props.comments) && <div>No comments</div>}
        <h3>Add a comment</h3>
        <CommentForm />
    </section>
);
}

const mapStateToProps = (state, props) => {
 return {"comments": state.comments}
};

export default connect(mapStateToProps)(Comments);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM