React Array.map无法将JSON数据识别为数组

时间:2018-08-28 18:36:17

标签: arrays json reactjs react-redux

这可能是一个非常简单的修复程序,但我无法弄清楚为什么map函数无法将输入识别为数组。

我有一个Dilemma模型,其中包含用户评论数组。我获取数据并将其映射到我的react组件的状态。然后,我尝试将数据作为道具解析到一个子组件,在该子组件中尝试映射数据。

减少困境

const initialState = {
  loading: false,
  dilemma: {}
};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_DILEMMA:
      return {
        ...state,
        dilemma: action.payload,
        loading: false
      };
    case GET_DILEMMAS:
      return {
        ...state,
        dilemmas: action.payload,
        loading: false
      };
    case CREATE_DILEMMA:
      return {
        ...state,
        dilemmas: [action.payload, ...state.dilemmas]
      };
    case DELETE_DILEMMA:
      return {
        ...state,
        dilemmas: state.dilemmas.filter(
          dilemma => dilemma._id !== action.payload
        )
      };
    case DILEMMAS_LOADING:
      return {
        ...state,
        loading: true
      };
    default:
      return state;
  }
}

this.props在有状态组件中

{
  "match": { "path": "/", "url": "/", "isExact": true, "params": {} },
  "location": { "pathname": "/", "search": "", "hash": "", "key": "crpcmj" },
  "history": {
    "length": 50,
    "action": "POP",
    "location": { "pathname": "/", "search": "", "hash": "", "key": "crpcmj" }
  },
  "dilemmas": {
    "loading": false,
    "dilemma": {
      "red_votes": 0,
      "blue_votes": 0,
      "_id": "5b855fcbdfa436e0d25765fa",
      "user": "5b855f9fdfa436e0d25765f9",
      "prefix": "Hvis du skulle vælge",
      "title": "Svede remoulade",
      "red": "Gå med rustning resten af dit liv",
      "blue": "Svede remoulade resten af dit liv",
      "likes": [],
      "comments": [
        {
          "date": "2018-08-28T17:28:23.340Z",
          "_id": "5b858637b6f6a6e6218eeaba",
          "user": "5b855f9fdfa436e0d25765f9",
          "text": "This is a test3 comment",
          "author": "Albyzai"
        },
        {
          "date": "2018-08-28T17:28:19.915Z",
          "_id": "5b858633b6f6a6e6218eeab9",
          "user": "5b855f9fdfa436e0d25765f9",
          "text": "This is a test2 comment",
          "author": "Albyzai"
        },
        {
          "date": "2018-08-28T15:50:18.792Z",
          "_id": "5b856f3aed156de48a270766",
          "user": "5b855f9fdfa436e0d25765f9",
          "text": "This is a test comment",
          "author": "Albyzai"
        }
      ],
      "date": "2018-08-28T14:44:27.413Z",
      "slug": "svede-remoulade",
      "__v": 3
    }
  },
  "errors": {}
}

状态组件

import React, { Component } from "react";
import propTypes from "prop-types";
import { connect } from "react-redux";
import { getDilemma, addLike, removeLike } from "../../actions/dilemmaActions";

import Dilemma from "./../dilemma/Dilemma";
import Divider from "./../dilemma/Divider";
import CommentFeed from "../dilemma/CommentFeed";

class DilemmaLayout extends Component {
  constructor() {
    super();
    this.state = {
      title: "",
      prefix: "",
      red: "",
      blue: "",
      red_votes: 0,
      blue_votes: 0,
      likes: [],
      comments: [],
      errors: {}
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }

    if (nextProps.dilemmas.dilemma) {
      const dilemma = nextProps.dilemmas.dilemma;

      this.setState({
        id: dilemma._id,
        user: dilemma.user,
        title: dilemma.title,
        prefix: dilemma.prefix,
        red: dilemma.red,
        blue: dilemma.blue,
        red_votes: dilemma.red_votes,
        blue_votes: dilemma.blue_votes,
        likes: [dilemma.likes],
        comments: [dilemma.comments]
      });
    }
  }

  render() {
    return (
      <div>        
        <CommentFeed comments={this.state.comments} />
      </div>
    );
  }
}

DilemmaLayout.propTypes = {
  getDilemma: propTypes.func.isRequired,
  addLike: propTypes.func.isRequired,
  removeLike: propTypes.func.isRequired,
  dilemmas: propTypes.object.isRequired
};

const mapStateToProps = state => ({
  dilemmas: state.dilemmas,
  errors: state.errors
});

export default connect(
  mapStateToProps,
  { getDilemma, addLike, removeLike }
)(DilemmaLayout);

功能部件接收道具

import React from "react";
import Comment from "./Comment";
import { Container } from "reactstrap";

const CommentFeed = comments => {
  const commentArray = comments.map(comment => {
    <Comment author={comment.author} text={comment.text} />;
  });

  return <Container>{commentArray}</Container>;
};

export default CommentFeed;

1 个答案:

答案 0 :(得分:2)

尝试使用类似ES6 destructuring assignment的东西从comments组件上的props提取道具CommentFeed /解包。这样做是因为comments数组直接传递给组件,而是将props对象传递给包含comments属性的组件

const CommentFeed = ({ comments }) => {
  const commentArray = comments.map(comment =>
    <Comment author={comment.author} text={comment.text} />;
  );

  return <Container>{commentArray}</Container>;
};

或访问comments,例如props.comments

const CommentFeed = props => {
  const commentArray = props.comments.map(comment =>
    <Comment author={comment.author} text={comment.text} />;
  );

  /* also an option
    const { comments } = props;
    const commentArray = comments.map(comment => {
      <Comment author={comment.author} text={comment.text} />;
    });
  */

  return <Container>{commentArray}</Container>;
};

此外,无法从提供的内容中分辨出来,但是以下几种状态设置可能会引起问题,原因有几个:

componentWillReceiveProps(nextProps) {
  if (nextProps.errors) {
    this.setState({ errors: nextProps.errors });
  }

  if (nextProps.dilemmas.dilemma) {
    const dilemma = nextProps.dilemmas.dilemma;

    this.setState({
      // ...
      likes: [dilemma.likes],
      comments: [dilemma.comments]
    });
  }
}
  1. 如果dilemma.likes是一个数组。您只需要likes: dilemma.likeslikes: [...dilemma.likes]
  2. 如果dilemma.comments是一个数组。您只需要comments: dilemma.commentscomments: [...dilemma.comments]

在创建嵌套数组(例如[[]])时,可能会导致您在comments.map()组件中的CommentFeed中描述的错误为map()的问题正在尝试访问嵌套数组项(例如author)的属性[{ "author":"Albyzai" }].author

鉴于componentWillReceiveProps将来会被弃用,为什么不只使用comments和来自商店的其他属性传递给子组件或渲染呢?您在评论中提到,在初始渲染时,各种道具未定义/为空。您可能需要结合商店的状态使用loading属性和某种条件渲染。

render() {
  const { dilemmas, errors } = this.props;

  if (errors) {
    return <div>{errors}</div>;
  } else if (!dilemmas.dilemma || dilemmas.loading) {
    return <div>Loading...</div>;
  } else {
    return <CommentFeed comments={dilemmas.dilemma.comments} />;
  }
}

我已经创建了一个StackBlitz,在基本级别上显示了此功能。

希望有帮助!

相关问题