简体   繁体   English

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

[英]Cannot access a nested array within an object in react-redux

我的 redux 状态层次结构

Hello, I am new to redux and I am struggling with a problem.你好,我是 redux 的新手,我正在努力解决一个问题。 I am trying to access and map over the comments within my post array.我正在尝试访问和映射我的帖子数组中的评论。 However, I am not sure how to do this.但是,我不确定如何执行此操作。 So far, I've tried changing the actions and reducers in order to solve this issue.到目前为止,我已尝试更改操作和减速器以解决此问题。 I think the problem is within the react and redux.我认为问题出在 react 和 redux 中。 I can't tell if my mapStateToProps is working correctly.我不知道我的 mapStateToProps 是否工作正常。 Also, the state is being fetched from my express server and it seems to be working properly as you can see in the picture.此外,状态是从我的快速服务器获取的,它似乎工作正常,如您在图片中看到的那样。

My getPost action:我的 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 }
    });
  }
};

The initial state:初始状态:

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

The reducer:减速机:

case GET_POST:
  return {
  ...state,
  post: payload,
  loading: false
};

Where I'm trying to map over the comments:我试图映射评论的地方:

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

You can access nested object with some tricks using redux, we have use this way in our prod env for some time.您可以使用 redux 使用一些技巧访问嵌套对象,我们在 prod env 中使用这种方式已有一段时间了。

First the reducer (you can make this reducer even more complex)首先是减速器(你可以让这个减速器更复杂)

const LocalStorageReducer = createReducer<Store['localStorage']>(
  new LocalStorage(),
  {
    saveLocalStorageItem(state: LocalStorage, action: any) {
      return {...state, [action.payload.item]: action.payload.value}; // <= here
    },
  }
);

For Actions对于行动

export const actions = {
  saveLocalStorageItem: (payload: InputAction) => ({type: 'saveLocalStorageItem', payload}),
};

For the type InputAction对于类型InputAction

export class InputAction {
  item: string;
  value: string | Array<string> | null | boolean;
  constructor() {
    this.item = '';
    this.value = null;
  }
}

For the handler in component对于组件中的处理程序

this.props.saveLocalStorage({ item: 'loading', value: false });

In this way you can go one way done to the nested redux store.通过这种方式,您可以通过一种方式完成嵌套的 redux 存储。
For complex (4-5 levels) and multiple (> 2 times) data structure, there are other ways, but in most situations, it's good enough.对于复杂(4-5级)和多重(>2次)的数据结构,还有其他方式,但在大多数情况下,已经足够了。

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

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