Javascript 无法访问react redux中对象内的嵌套数组

Javascript 无法访问react redux中对象内的嵌套数组,javascript,reactjs,express,redux,react-redux,Javascript,Reactjs,Express,Redux,React Redux,你好,我是redux的新手,我正在努力解决一个问题。我正在尝试访问并映射我的帖子数组中的评论。然而,我不知道如何做到这一点。到目前为止,为了解决这个问题,我已经尝试了更改操作和减缩器。我认为问题出在react和redux中。我不知道我的mapStateToProps是否工作正常。此外,正在从我的express服务器获取状态,正如图中所示,它似乎工作正常 我的getPost操作: export const getPost = (group_id, post_id) => async disp

你好,我是redux的新手,我正在努力解决一个问题。我正在尝试访问并映射我的帖子数组中的评论。然而,我不知道如何做到这一点。到目前为止,为了解决这个问题,我已经尝试了更改操作和减缩器。我认为问题出在react和redux中。我不知道我的mapStateToProps是否工作正常。此外,正在从我的express服务器获取状态,正如图中所示,它似乎工作正常

我的getPost操作:

export const getPost = (group_id, post_id) => async dispatch => {
  try {
    const res = await axios.get(`/api/groups/${group_id}/${post_id}`);

    dispatch({
      type: GET_POST,
      payload: res.data
    });
  } catch (error) {
    dispatch({
      type: POST_ERROR,
      payload: { msg: error.response.statusText, status: error.response.status }
    });
  }
};
初始状态:

const initialState = {
  groups: [],
  group: [],
  loading: true,
  error: {}
};
减速器:

case GET_POST:
  return {
  ...state,
  post: payload,
  loading: false
};
我试图将这些评论映射到以下位置:

import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getPost } from '../../../redux/actions/group';

const Post = ({ getPost, post, match }) => {
  useEffect(() => {
    getPost(match.params.group_id, match.params.post_id);
  }, [getPost, match.params.group_id, match.params.post_id]);

  // I want to map over the comments here
  return (
      {post.comments.map(comment => ({ comment }))}
  );
};

Post.propTypes = {
  getPost: PropTypes.func.isRequired,
  group: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  post: state.post
});

export default connect(mapStateToProps, { getPost })(Post);

您可以使用redux使用一些技巧访问嵌套对象,我们在prod env中使用这种方法已有一段时间了

首先是减速器(您可以使此减速器更加复杂)

对于类型
inputation

export class InputAction {
  item: string;
  value: string | Array<string> | null | boolean;
  constructor() {
    this.item = '';
    this.value = null;
  }
}
通过这种方式,您可以单向访问嵌套的redux存储。

对于复杂(4-5级)和多个(>2倍)的数据结构,还有其他方法,但在大多数情况下,已经足够好了

这些元素似乎是一组对象。您能否更新该对象的结构以及要显示的内容。仅供参考,我们不能显示任何物体。你好,@Vishnu。我正试图展示这篇文章。这篇帖子会有回复的评论。基本上,如果你点击帖子,我会显示帖子的所有评论。我知道了,但是评论不是字符串。因此,如果注释的形状类似于
{comment:'foo',author:'bar'}
,您可以像
{post.comments.map(comment=>(comment:{comment.comment}{comment.author}))}
,,PS:根据您希望布局的方式:v@Vishnu我以前尝试过这样做,但它给了我TypeError:无法读取未定义的属性“comments”。我不认为我可以访问帖子,除非我通过组。初始状态是缺少帖子。您可以使用
{}
初始化post,并添加一个check-in返回语句,如
{post.comments&&post.comments.map(..
export const actions = {
  saveLocalStorageItem: (payload: InputAction) => ({type: 'saveLocalStorageItem', payload}),
};
export class InputAction {
  item: string;
  value: string | Array<string> | null | boolean;
  constructor() {
    this.item = '';
    this.value = null;
  }
}
this.props.saveLocalStorage({ item: 'loading', value: false });