reactjs - 试图列出对象中的项目,其中一个是数组....不断出错
问题描述
我已经尝试过这里列出的问题的其他答案,但它们不起作用。我在做什么不同?
我有一个应用程序,我想在其中列出一个主题,该主题具有与之关联的评论列表/数组。当用户点击“添加主题”链接时,用户将看到一个随机生成的主题,该主题与过去的评论相关联,并且还有机会添加新评论。我可以打印出主题,但无法打印出评论。我什至可以在控制台中打印出评论,但不能在页面上。该错误表示注释未定义。我究竟做错了什么?这是代码:
主题.js
import React, { Component } from 'react';
import axios from "axios";
import { withRouter } from 'react-router-dom';
import { createComment, listTopicWithComments } from '../util/APIUtils';
import './Topic.css';
import TopicComp from '../components/TopicComp';
import { Form, Input, Button, Icon, Select, Col, notification } from 'antd';
const URL='http://localhost:8080/api/auth/randomtopic';
const URL2='http://localhost:8080/api/auth/topic/';
const Option=Select.Option;
const FormItem = Form.Item;
const {TextArea}= Input
class Topic extends Component {
constructor(props) {
super(props);
this.state = {
topic: {},
comment: {
text:''
}
};
this.handleSubmit=this.handleSubmit.bind(this);
this.isFormInvalid=this.isFormInvalid.bind(this);
this.handleCommentChange=this.handleCommentChange.bind(this);
//this.listTopicWithComments=this.listTopicWithComments.bind(this);
}
handleSubmit(event){
event.preventDefault();
const commentData= this.state.comment.text;
const commentTopicid= this.state.topic.id;
console.log("commentdata:", commentData);
console.log("topicid: ", commentTopicid);
createComment(commentData,commentTopicid)
.then(response => {
console.log("response comment: ", response.data);
this.props.history.push("/");
}).catch(error => {
if(error.status === 401){
this.props.handleLogout('/login', 'error', 'You have been logged out. Please login and choose randome topic.');
}else {
notification.error({
message: 'Social-J App',
description: error.message || 'Sorry, something went wrong.'
});
}
});
listTopicWithComments(commentTopicid)
.then(response => {
console.log("topic comment", response.data);
this.props.history.push("/");
});
}
validateComment = (commentText) => {
if(commentText.length === 0) {
return {
validateStatus: 'error',
errorMsg: 'Please enter your comment!'
}
} else if (commentText.length > 150) {
return {
validateStatus: 'error',
errorMsg: `Comment is too long (Maximum 150 characters allowed)`
}
} else {
return {
validateStatus: 'success',
errorMsg: null
}
}
}
handleCommentChange(event) {
const value = event.target.value;
this.setState({
comment: {
text: value,
...this.validateComment(value)
}
});
}
componentDidMount(){
if(this.props.isAuthenticated){
axios.get(URL)
.then((response) =>
{
console.log("response", response.data);
this.setState({topic:response.data})
})
.catch((err) => {
console.log(err);
});
}
}
isFormInvalid() {
if(this.state.comment.validateStatus !== 'success') {
return true;
}
}
render() {
//console.log("URL used: ",URL);
//console.log("new topic",this.state.topic.id);
//console.log("new topic",this.state.topic.topic);
const topicId = this.state.topic.id;
const uDate = this.state.topic.expirationDateTime;
const oldComments=this.state.topic.comments;
console.log("topicid: ", topicId);
console.log("date: ", uDate);
console.log("oldcomments: ", oldComments );
//return nComment;
return (
<div className="new-comment-container">
<h1 className="page-title">{this.state.topic.topic}</h1>
<div>
{this.state.topic.comments.map(comment =>{
return <div key={comment.id}>
{comment.comment}
</div>
})}
</div>
<div className="new-comment-content">
<Form onSubmit={this.handleSubmit} className="create-comment-form">
<FormItem validateStatus={this.state.comment.validateStatus}
help={this.state.comment.errorMsg} className="comment-form-row">
<TextArea placeholder="Enter comment" style={{ fontSize: '16px'}}
autosize={{minRows:3, maxRows: 6}}
name="comment"
value={this.state.comment.text}
onChange={this.handleCommentChange} /></FormItem>
<FormItem className="comment-form-row">
<Button type="primary" htmlType="submit" size="large"
disabled={this.isFormInvalid()}
className="create-comment-form-button">Add Comment</Button>
</FormItem>
</Form>
</div>
<div>
hi
</div>
</div>
)}
}
export default withRouter(Topic);
这是错误:
TypeError: this.state.topic.comments is undefined
render
client/src/components/Topic.js:134
131 | <div className="new-comment-container">
132 | <h1 className="page-title">{this.state.topic.topic}</h1>
133 | <div>
> 134 | {this.state.topic.comments.map(comment =>{
135 | return <div key={comment.id}>
136 | {comment.comment}
137 | </div>
解决方案
那是因为变量 this.state.topic.comments 没有值
推荐阅读
- node.js - 我怎样才能正确地做出响应中的 fetch api 调用?
- tensorflow - Sparkfun 边缘消息“!!!有线升级不成功!!!....终止脚本”
- python - 列表中的连续字符
- python - tf.set_random_seed 似乎没有正确设置种子
- ios - 无法在 Xcode 11 beta 中选择自定义字体?
- typescript - 如何根据属性优化合并两个不同对象的数组?
- go - 在 Gin 框架中,寻找值开头的无效字符“P”
- netsuite - Netsuite通过suitelet中的按钮删除记录
- solr - 无法实现lucene solr代码调试
- java - 如何在android中共享带有意图的图像位图?