从json响应中迭代内部数组

时间:2018-06-17 13:49:35

标签: reactjs redux

我有这个json响应,我想渲染 post_comment 字段。

response.json:

{
    "id": 2,
    "tags": [],
    "post_comment": [
        {
            "id": 2,
            "author_comment": 45,
            "comment_body": "xgdgfdf",
            "created_date": "2018-06-13T12:55:52.460282Z",
            "post": 2
        },
        {
            "id": 3,
            "author_comment": 45,
            "comment_body": "asdsasd",
            "created_date": "2018-06-13T13:45:01.535194Z",
            "post": 2
        },
        {
            "id": 4,
            "author_comment": 45,
            "comment_body": "asdsasdDasdasdasdasdasdadadadadadaaaaaaaaaaaaaadddddddd",
            "created_date": "2018-06-13T13:46:18.721375Z",
            "post": 2
        },

    ],
    "url": "http://127.0.0.1:8000/api/post/2/",
    "author_name": "",
    "title": "god of war",
    "body": "this is the god of war ..I Fdfwfdwdfound the solution, i just have to tell django to try connecting using the original backend if the user isnt a student or professor. just add 'django.sdfdsdfsfsfsy",

    "slug": "god-of-war",
    "publish_date": "2018-06-12T10:27:07.100113Z",
    "author": 45
}

这是我的 postDetailomponent

class postDetailComponent extends Component {

  componentDidMount(){
    this.props.fetchPostDetail(this.props.match.params.id);

  }

  render(){
    const { post } = this.props;
    if (!post) {
      return <div>loading </div>;
    }
    return (
      <div className='container' >
        <h1>{post.title}</h1>
        <p>{post.body}</p>
        <h6>{post.publish_date}</h6>
        <h6>{post.tags}</h6>
        <div >


    );

  }
}
function mapStateToProps(state) {
  return { post: state.postDetail.post};
}

我尝试通过 post_comment 进行映射,但它反应说:

const comments = post.post_comment.map((comment) => <li>{comment.comment_body}</li>);
  

未捕获的TypeError:无法读取属性&#39; map&#39;未定义的

所以我怎么能在json中呢?我的全部观点是:我的所有数据都在那里并正确渲染但我无法渲染post_comment因为这是一个多对象。即使我尝试设置评论的密钥。但是无法正常工作。

1 个答案:

答案 0 :(得分:3)

将maping语句更改为,

render_id: 1323
player_id: 30
origin_url: https://example.com
frame_url: https://example.com
frame_title: Example
url: blob:https://example.com
info: Selected GpuVideoDecoder for video decoding, config: codec: h264 format: 1 profile: h264 main coded size: [848,480] visible rect: [0,0,848,480] natural size: [848,480] has extra data? false encrypted? false rotation: 0°
pipeline_state: kSuspended
found_audio_stream: true
audio_codec_name: aac
found_video_stream: true
video_codec_name: h264
audio_dds: false
audio_decoder: FFmpegAudioDecoder
video_dds: false
video_decoder: GpuVideoDecoder
audio_buffering_state: BUFFERING_HAVE_ENOUGH
video_buffering_state: BUFFERING_HAVE_ENOUGH
height: 480
width: 848
pipeline_buffering_state: BUFFERING_HAVE_ENOUGH
duration: 39.50686

最初在api调用之前,这个props值将是未定义的,因此处理该条件应该可以解决问题。