我正在调用 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"}}