【发布时间】:2018-04-12 05:18:49
【问题描述】:
我不断收到类型错误:无法读取属性... 我将状态设置为来自 fetch 响应的 JSON 对象。对象的 String 和 Date 属性似乎渲染得很好,但 Array 和 Number 属性不断出现类型错误。
class ViewPost extends Component {
state = {
post: {}
}
constructor(props) {
super(props);
this.setPostState = this.setPostState.bind(this);
}
componentWillMount() {
this.setPostState();
}
setPostState() {
let postTitle = this.props.match.params.id;
fetch('/posts/getpost', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: postTitle
})
})
.then(res => res.json())
.then(post => this.setState({ post }))
}
render() {
return (
<div className="Post">
<div className="card">
<img className="img-fluid" src="/img/darkstockphoto.jpg" alt="Post"/>
<div className="card-body">
<h4 className="card-title">{this.state.post.title}</h4>
<p className="card-text">{this.state.post.author}</p>
<p className="card-text">{this.state.post.date}</p>
<p className="card-text">{this.state.post.body}</p>
</div>
</div>
<hr />
{this.state.post.comments && this.state.post.comments.map(comment => (
<div key={comment.author + comment.date} className="card card-body">
<h4 className="card-title">{comment.title}</h4>
</div>
))}
</div>
);
}
}
export default ViewPost;
【问题讨论】:
-
查看此答案*.com/questions/47027035/…。此外,由于 this.state.post 最初是空的,因此也可以渲染
this.state.post.title和其他有条件的事情,就像您为 cmets 所做的那样
标签: javascript reactjs