javascript - 无法从 REACT 中的 JSON 调用访问单个对象中的嵌套对象属性

标签 javascript json reactjs

我正在调用 Rails API 并返回一个包含嵌套用户对象和标签列表数组的 JSON 对象。但是,我无法访问嵌套对象。

this.props.post.user.name 抛出: 无法读取未定义的属性“名称”。

我很困惑,因为当我调用 PostsIndex.js 中的 PostsIndex 并获取对象数组并通过它进行映射时,我可以访问所有内容。

当只处理单个对象时,我需要做些什么吗?

PostShow.js

import React, {Component} from 'react';
import axios from 'axios';
import {Link} from 'react-router-dom';



export default class PostShow extends Component {

constructor(props) {
  super(props)
  this.state = {
    post: {}
  };
}

componentDidMount() {
  const { match: { params } } = this.props;
  axios
    .get(`/api/posts/${params.postId}`)
    .then(response => {
      console.log(response);
      this.setState({ post: response.data});
    })
    .catch(error => console.log(error));

}

  render() {
    return (
      <div>
            <Post post={this.state.post}/>
      </div>
    );
  }
}

class Post extends Component {

  constructor(props) {
    super(props)
  }

  render() {

    return (
      <div>
        <div className="centered">
          <small className ="small" >  | Posted by: {this.props.post.user.name}  on   | Tags:  </small>
          <h3>{this.props.post.title}</h3>
          <img className="image " src={this.props.post.image}/>
        </div>
        <div>
          <p className = "songTitle"> {this.props.post.song_title} </p>
          <p className= "postBody"> {this.props.post.body} </p>
          <div className = "link" dangerouslySetInnerHTML={{ __html: this.props.post.link }} />
        </div>
      </div>
    );
  }
} 

这是来自/api/posts/7 的 JSON 对象:

{“身份证”:7, “标题”:“adgaadg”, “ body ”:“adgadgagdgd”, "post_type":"视频", “标签列表”:[“ERL”], “图像”:“/images/original/missing.png”, "song_title":"adgdgdgd", “创建时间”:“2018-08-11T21:57:00.447Z”, "user":{"id":2,"name":"John","bio":"bio","location":"Reno"}}

最佳答案

那是因为 this.props.post.user 在您的请求完成之前将是 undefined ,并且尝试访问 name 将会引起你的错误。

例如,您可以将初始 post 设置为 null 并且在您的请求完成之前不呈现任何内容。

示例

class PostShow extends Component {
  constructor(props) {
    super(props);
    this.state = {
      post: null
    };
  }

  componentDidMount() {
    const {
      match: { params }
    } = this.props;
    axios
      .get(`/api/posts/${params.postId}`)
      .then(response => {
        console.log(response);
        this.setState({ post: response.data });
      })
      .catch(error => console.log(error));
  }

  render() {
    const { post } = this.state;

    if (post === null) {
      return null;
    }

    return (
      <div>
        <Post post={post} />
      </div>
    );
  }
}

关于javascript - 无法从 REACT 中的 JSON 调用访问单个对象中的嵌套对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804796/

相关文章:

javascript - 迭代生成器的更简单方法?

javascript - 如何在带 meteor 的 Handlebars 助手中使用多个参数?

javascript - 用另一个数组过滤数组

reactjs - react : Cannot Login if url entered manually into the browser

javascript - 如何翻译 react-router 路由路径

javascript - 谷歌浏览器和 FPS 的奇怪行为

javascript - FlatList 与 map react-native

c# - 使 WCF 服务接受来自 jQuery.AJAX() 的 JSON 数据

java - 在Mysql或Oracle数据库中加载一个大的json文件

javascript - Firebase Web 客户端将 JSON 上传到 Cloud Storage