javascript - 映射 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
/>
谢谢!
解决方案
你的getTeacherName()
方法应该选择正确的老师,然后返回名字如下。
getTeacherName = () => {
let teacherObj = this.props.teachers.find(teacher => (teacher.id == this.props.match.params.id));
return teacherObj ? teacherObj.name : null;
};
推荐阅读
- machine-learning - pycolab 和 AI 安全网格世界入门
- php - Laravel 有关于 where 的功能
- angular - 无法将 css 应用于 mat-icon 内的 svg 图标
- vue.js - vue js 使用 npm 模块作为内联脚本
- c# - 链接 TransformBlock 产生 IEnumerable
阻止接收 T - c# - 如何通过 REST API 传输图像?(内有Core 2.0)
- java - Java 长字节长度
- java - java.lang.ClassCastException:实现 parcelable 时无法转换为 java.lang.String
- excel - COUNTIF 日期出现在同一周数和年份
- java - 检测动态 IP 地址变化