首页 > 解决方案 > 映射 props(名称数组)返回带有逗号字符串的名称(“Pam,,,,,,,,,,,,,,,”)——数组中的每个项目对应一个

问题描述

我正在映射 React 组件中的 20 个字符串数组。该数组已作为来自父级的 props 传递给此组件。当我将函数的结果传递给 JSX 元素(一个 h1)时,它只返回名称。当我将相同的函数传递给表单的占位符时,它会返回名称后跟 20 个逗号。如果我更改 ID 以便 map 函数从数组中间返回一个不同的字符串,它会返回名称,两边各有 10 个逗号。返回数组中的最后一项,名称前有 20 个逗号。

我试过让函数返回 null 或空字符串,或者只是没有“else”。

这是功能:

 getTeacherName = () => {
    return this.props.teachers.map(teacher => {
      if (teacher.id == this.props.match.params.id) {
        return teacher.name;
      } else {
        return null;
      }
    });
  };

这是我使用它并获得所需响应的地方:

return (
    <h1>{this.getTeacherName()}'s Schedule</h1>
)

这是我使用它并遇到问题的地方:

<input
  type="text"
  className="form-control"
  placeholder={this.getTeacherName()}
  disabled
/>

这是我所看到的屏幕截图。

谢谢!

标签: javascriptreactjsjsx

解决方案


你的getTeacherName()方法应该选择正确的老师,然后返回名字如下。

getTeacherName = () => {
    let teacherObj = this.props.teachers.find(teacher => (teacher.id == this.props.match.params.id));
     return teacherObj ? teacherObj.name : null;

  };

推荐阅读