[英]ERROR TypeError: Cannot read property 'toLowerCase' of undefined for Pipe
I have this pipe and this error in the title.我有这个 pipe 和标题中的这个错误。
Probably if any values from the array being undefined
is ok, but how to avoid this error?可能如果undefined
数组中的任何值都可以,但是如何避免此错误?
export class MusclePipe implements PipeTransform {
transform(muscle, searchTerm: string): MuscleComponent {
if (!muscle || !searchTerm) {
return muscle;
}
return muscle.filter(
(muscle) =>
muscle.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1
);
}
}
Usually, it means a name
property doesn't exist on one or more of the muscle
objects you are iterating through.通常,这意味着您正在迭代的一个或多个muscle
对象上不存在name
属性。
Ideally, you want to make sure data exists.理想情况下,您希望确保数据存在。 But in your case, if there is a possibility that it doesn't, the easiest (and the minimally correct) way is to use optional chaining (?.) after the key that could potentially be optional:但是在您的情况下,如果有可能不是,最简单(也是最低限度正确)的方法是在可能是可选的键之后使用可选链接(?。):
transform(muscle: [], searchTerm: string): MuscleComponent {
....
return muscle.filter(muscle =>
muscle.name?.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1);
}
}
(note the ?
after muscle.name
). (注意muscle.name
后的?
)。
But since you are chainig the method calls, you could do something like this:但由于您正在调用方法调用,您可以执行以下操作:
return muscle.filter(muscle => {
muscle.name && searchTerm
? muscle.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
: 'alternative return value';
}
}
Here we are using the ternary operator (if..else) to explicitly check for the value and return an alternative value.在这里,我们使用三元运算符 (if..else) 来显式检查值并返回替代值。 I also added the check for the searchTerm
is it may potentially be undefined too:我还添加了对searchTerm
的检查是否也可能未定义:
muscle.name && searchTerm
You should also include a check in case the muscle doesn't have the name
property defined correctly as it appears this is the error you have.如果肌肉没有正确定义name
属性,您还应该进行检查,因为这似乎是您遇到的错误。
export class MusclePipe implements PipeTransform {
transform(muscle, searchTerm: string): MuscleComponent {
if (!muscle || !muscle.name || !searchTerm) {
return muscle;
}
return muscle.filter(
(muscle) =>
muscle.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1
);
}
}
Add a null/undefined check in your pipe to check if the string is null before calling .toLowerCase
在调用 .toLowerCase 之前,在 pipe 中添加一个空/未定义检查以检查字符串是否为.toLowerCase
if (str === undefined) return [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.