如何在React组件内渲染另一个React组件

3

我正在学习React,并尝试在其中渲染<Comment/>组件,但是我遇到了以下错误:

TypeError: Cannot read property 'map' of undefined
Comment._this.getResponses
src/Comment.js:28
  25 |   );
  26 | }
  27 | getResponses = () => {
> 28 |   return this.props.responses.map(p => {
     | ^  29 |     return (
  30 |       <Comment
  31 |         author={p.author}

以及代码:

import React, { Component } from "react";

class Comment extends Component {
  render() {
    return (
      <div className="comment">
        <a className="avatar">
          <img src={this.props.avatar} />
        </a>
        <div className="content">
          <a className="author">{this.props.author}</a>
          <div className="metadata">
            <span className="date">{this.props.timeStamp}</span>
          </div>
          <div className="text">
            <p>{this.props.text}</p>
          </div>
          <div className="actions">
            <a className="reply">Reply</a>
          </div>
        </div>
        <div className="comments">{this.getResponses()}</div>
      </div>
    );
  }
  getResponses = () => {
    return this.props.responses.map(p => {
      return (
        <Comment
          author={p.author}
          avatar={p.avatar}
          timeStamp={p.timeStamp}
          text={p.text}
        />
      );
    });
  };
}

export default Comment;

请注意,this.props.responses不是undefined,问题只出现在我尝试使用Comment组件时。如果我在这里替换Comment组件:
return this.props.responses.map(p => {
  return <Comment
      author={p.author}
      avatar={p.avatar}
      timeStamp={p.timeStamp}
      text={p.text}
    />
});

使用类似以下的方式:
return this.props.responses.map(p => {
  return (
    <div>
      <h1>author={p.author}</h1>
      <h1>avatar={p.avatar}</h1>
      <h1>timeStamp={p.timeStamp}</h1>
      <h1>text={p.text}</h1>
    </div>
  );
});

代码运行正常。

1个回答

3
这是因为渲染<Comment />依赖于定义responses属性。当前,当您在getResponses()中渲染Comment组件时,这些评论中没有分配responses属性:
<Comment
      author={p.author}
      avatar={p.avatar}
      timeStamp={p.timeStamp}
      text={p.text}
    />

这意味着当渲染这些 <Comment /> 组件并试图通过未定义的 responses 属性去渲染其自身的“children”(在调用 getResponses() 时)时,会抛出错误。
要解决此问题,您可以在进行映射和渲染 <Comment/> 组件之前,先检查 this.props.responses 数组是否已定义,例如:
getResponses = () => {

    // Check that responses prop is an array before
    // attempting to render child Comment components
    if(!Array.isArray(this.props.responses)) {
        return null;
    }

    return this.props.responses.map(p => {
      return (
        <Comment
          author={p.author}
          avatar={p.avatar}
          timeStamp={p.timeStamp}
          text={p.text}
        />
      );
    });
  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接