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

IT技术 javascript json reactjs
2021-05-07 16:34:05

我正在调用 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 对象的样子:

{"id":7, "title":"adgaadg", "body":"adgadgagdgd", "post_type":"Video", "tag_list":["ERL"], "image":"/images/original/missing.png", "song_title":"adgdgdgd", "created_at":"2018-08-11T21:57:00.447Z", "user":{"id":2,"name":"John","bio":"bio","location":"Reno"}}

2个回答

那是因为this.props.post.userundefined在您的请求完成之前,并尝试访问name它会导致您的错误。

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

例子

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

axios.get是一个异步操作并在<Post post={this.state.post}/>渲染之前渲染,this.setState({ post: response.data});这意味着 Post 组件渲染时this.state.post为空对象。所以你可以做的是,在构造函数中用 null 初始化你的帖子

this.state = {
   post: null
};

而不是<Post post={this.state.post}/>do{this.state.post && <Post post={this.state.post}/>}它只会在 post 存在且不为 null 时呈现 post。