无法访问React组件中的Redux状态

时间:2018-01-24 08:19:17

标签: javascript reactjs redux

我正在尝试将redux状态显示在我的react组件中。我的root reducer看起来像这样:

index.js

import { combineReducers } from 'redux';
import PostReducer from './PostsReducer';
import { reducer as formReducer} from 'redux-form';
import CategoriesReducer from './CategoriesReducer';
import CommentsReducer from './CommentsReducer';

const rootReducer = combineReducers({
    posts: PostReducer,
    categories: CategoriesReducer,
    comments: CommentsReducer,
    form : formReducer
});

export default rootReducer;

现在,我在访问评论状态时遇到问题。我的评论Rededcer reducer如下所示:

CommentsReducer.js

import { FETCH_COMMENTS } from '../actions/comment_action';

export default function(state={}, action) {
    switch (action.type) {
      case FETCH_COMMENTS:
          return {comments: {...state.comments, ...action.payload.data}};

      default:
        return state;
    }
}

在我的组件中,我试图在mapStateToProps方法中获取状态,如下所示:

function mapStateToProps({ posts, comments }, ownProps) {
    return {
      post: posts[ownProps.match.params.id],
      comment: comments[ownProps.match.params.id]};
}

现在,在我的渲染功能中,如果我尝试将注释状态设置为 {this.props.comments} ,我会收到null。我的意思是它没有显示任何内容。我该怎么办?

编辑1:添加州的屏幕截图: state

编辑2 条件渲染:

{
            (createStoreWithMiddleware.getState().comments) ?

              <div>
                  {this.props.comment}
              </div>
                                                  :
              <div>
                Null
              </div>

          }

编辑3 :api服务器中的Comment.js文件。

const defaultData = {
  "894tuq4ut84ut8v4t8wun89g": {
    id: '894tuq4ut84ut8v4t8wun89g',
    parentId: "8xf0y6ziyjabvozdd253nd",
    timestamp: 1468166872634,
    body: 'Hi there! I am a COMMENT.',
    author: 'thingtwo',
    voteScore: 6,
    deleted: false,
    parentDeleted: false
  },
  "8tu4bsun805n8un48ve89": {
    id: '8tu4bsun805n8un48ve89',
    parentId: "8xf0y6ziyjabvozdd253nd",
    timestamp: 1469479767190,
    body: 'Comments. Are. Cool.',
    author: 'thingone',
    voteScore: -5,
    deleted: false,
    parentDeleted: false
  }
}

我的API端点描述如下:

GET /comments/:id
      USAGE:
        Get the details for a single comment

编辑4 输出的屏幕截图。 devtools

3 个答案:

答案 0 :(得分:1)

由于您在mapStateToProps中使用了“comment”。

您可以使用{this.props.comment}访问它而不是{this.props.comments}

如果有帮助,请告诉我。

答案 1 :(得分:1)

你必须从react-redux导入connect方法然后使用mapStateToProps到connect方法,如:

      import { connect } from 'react-redux';
      class ComponentName extends Component {
      }
      function mapStateToProps({ posts, comments }, ownProps) {
        return {
            post: posts[ownProps.match.params.id],
            comment: comments[ownProps.match.params.id]};
      }  
      export default connect(mapStateToProps)(ComponentName);

答案 2 :(得分:1)

您需要检查一些事项

首先:以下reducer是评论缩减器,state.comments未定义,因此...state.comments将失败。所以你需要像state = {comments: {}}

那样更新initialState
import { FETCH_COMMENTS } from '../actions/comment_action';

export default function(state = {comments: {}}, action) {
    switch (action.type) {
      case FETCH_COMMENTS:
          return {comments: {...state.comments, ...action.payload.data}};

      default:
        return state;
    }
}

第二:mapStateToProps function mapStateToProps({ posts, comments }, ownProps) {帖子中,组件是缩减器,因此posts[ownProps.match.params.id]comments[ownProps.match.params.id]不是您想要的,但

function mapStateToProps({ posts, comments }, ownProps) {
    return {
      post: Object.values(posts.posts).find(post => post.id ===ownProps.match.params.id),
      comment: Object.values(comments.comments).find(comment => comment.id ===ownProps.match.params.id};
}

第三:现在使用fetchComments操作更新注释,您应该在组件中使用它之前检查注释,如

if(this.props.comment) {
    //do what you want with comment here
}

或者如果您在JSX中使用它,请像

一样使用它
{this.props.comment ? <div>{this.props.comment}</div>: null}