我不断收到类型错误:无法读取属性...
我将从获取响应中将状态设置为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;
最佳答案
setState是异步的,因此您需要这样处理this.state.post
:
render() {
if (this.state.post) {
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>);
}
return null;
}
关于javascript - React无法呈现状态属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47028612/