我正在 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
/>
Here is a screenshot of what I'm seeing.
谢谢!
最佳答案
您的 getTeacherName()
方法应该选择正确的教师,然后按如下方式返回姓名。
getTeacherName = () => {
let teacherObj = this.props.teachers.find(teacher => (teacher.id == this.props.match.params.id));
return teacherObj ? teacherObj.name : null;
};
关于javascript - 映射到 Prop (名称数组)返回带有逗号字符串的名称 ("Pam,,,,,,,,,,,,,,,") - 数组中的每个项目一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157116/