reactjs - 尝试打印具有数组的对象时出现错误

标签 reactjs axios react-router-dom

我已经尝试了此处列出的问题的其他答案,但它们不起作用。我做了什么不同的事情?

我有一个应用程序,我想在其中列出一个主题,该主题具有与其关联的评论列表/数组。当用户点击“添加主题”链接时,用户将看到生成的随机主题以及与其关联的过去评论,并且还有添加新评论的机会。我可以打印主题,但无法打印评论。我什至可以打印控制台中的注释,但不能打印在页面上。

错误表明注释未定义。我做错了什么?

这是代码:

topic.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);

这是错误。类型错误:

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>

最佳答案

您正在尝试在加载 topic 之前使用 this.state.topic.comments

你可以例如最初将主题设置为 null 并从渲染返回 null 直到它被设置。

示例

class Topic extends Component {
  constructor(props) {
    super(props);
    this.state = {
      topic: null,
      comment: {
        text: ""
      }
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.isFormInvalid = this.isFormInvalid.bind(this);
    this.handleCommentChange = this.handleCommentChange.bind(this);
  }

  render() {
    const { topic } = this.state;

    if (topic === null) {
      return null;
    }

    // ...
  }
}

关于reactjs - 尝试打印具有数组的对象时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756866/

相关文章:

javascript - 如何设置axios超时

javascript - react-router 在生产和激增部署中不起作用

javascript - ReactJS 路由组件/渲染

reactjs - React - _this2.SetState 不是一个函数

javascript - 服务 png 图像的 Axios 图像损坏

javascript - React 在渲染之前为字符串的特定部分提供样式?

javascript - React - 使用外部 URL 时未定义 Map 函数

reactjs - React router - 如果在 url 中输入父组件路径,如何重定向到子组件

javascript - 处理从 props 传递的数据排序的最佳方法是什么?

node.js - 仍使用IE显示页面上不存在的旧数据