简体   繁体   English

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

[英]Unable to access Redux state in React component

I am trying to display the redux state into my react component.My root reducer looks this: 我试图将redux状态显示在我的react组件中。我的root reducer看起来像这样:

index.js 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;

Now,I am facing issues in accessing my comments state.My CommentsReducer reducer is as shown below: 现在,我在访问我的评论状态时遇到了问题。我的评论 Rededcer reducer如下所示:

CommentsReducer.js 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;
    }
}

In my component,I am trying to get the state in my mapStateToProps method as follows: 在我的组件中,我试图在mapStateToProps方法中获取状态 ,如下所示:

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

Now, in my render function if I try to get the comments state as {this.props.comments} , I receive null.I mean it does not display anything.How do I proceed? 现在,在我的渲染函数中,如果我尝试将注释状态设置为{this.props.comments} ,我会收到null。我的意思是它没有显示任何内容。我该怎么办?

EDIT 1: Adding screenshot of the state: 编辑1:添加州的屏幕截图: 州

EDIT 2 Conditional rendering: 编辑2条件渲染:

{
            (createStoreWithMiddleware.getState().comments) ?

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

          }

EDIT 3 : Comment.js file in the api server. 编辑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
  }
}

And my API endpoint is described as shown below: 我的API端点描述如下:

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

EDIT 4 Screenshot of the output. 编辑4输出的屏幕截图。 devtools

Since you have used "comment" in your mapStateToProps. 由于您在mapStateToProps中使用了“comment”。

You can access it using {this.props.comment} and not {this.props.comments} 您可以使用{this.props.comment}访问它而不是{this.props.comments}

Let me know if this helps. 如果这有帮助,请告诉我。

You have to import connect method from react-redux then use mapStateToProps into connect method like: 你必须从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);

There are a few things that you need to check 您需要检查一些事项

First: The below reducer is a comment reducer and state.comments is not defined so ...state.comments will fail. 第一:下面的reducer是一个评论减速器, state.comments没有定义,所以...state.comments将失败。 So you need to update the initialState like state = {comments: {}} 所以你需要更新initialState,如state = {comments: {}}

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;
    }
}

Second: In mapStateToProps function mapStateToProps({ posts, comments }, ownProps) { posts and components are reducers and hence posts[ownProps.match.params.id] and comments[ownProps.match.params.id] is not what you want but 第二:mapStateToProps function mapStateToProps({ posts, comments }, ownProps) { posts和components是reducers,因此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};
}

Third: Now that comments are updated using fetchComments action, you should make a check for comment before using it in the component like 第三:现在使用fetchComments操作更新注释,您应该在组件中使用它之前检查注释

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

or if you are using it in JSX, use it like 或者如果您在JSX中使用它,请使用它

{this.props.comment ? <div>{this.props.comment}</div>: null}

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

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