[英]Uncaught TypeError: Cannot convert undefined or null to object React
I'm having a strange problem with my code.我的代码有一个奇怪的问题。 There is an object that comes from an API call where videos are stored and I need to add the number of videos on the website.
有一个 object 来自 API 调用,其中存储了视频,我需要在网站上添加视频数量。 But sometimes there can be "null" coming from API call and obviously, I don't have to show the length of the null value.
但有时 API 调用可能会出现“null”,显然,我不必显示 null 值的长度。
As I wrote this code which works when I try on editors, but when I use it on my project it gives an error Cannot convert undefined or null to object.当我编写此代码时,该代码在我尝试使用编辑器时有效,但是当我在我的项目中使用它时,它会给出错误无法将未定义或 null 转换为 object。 Can anyone give me an idea or hint of what I'm doing wrong?
谁能给我一个想法或暗示我做错了什么? And sorry if I explained unclearly, this is my very first post here.
抱歉,如果我解释不清楚,这是我在这里的第一篇文章。 Thank you!
谢谢!
const object = {
background_video: null,
vimeo_branded: 'video url',
vimeo_unbranded: "video url"
}
const removeFalsyElement = object => {
let sum = 0;
Object.keys(object).forEach(key => {
if (object[key]) {
sum += 1;
}
});
return sum;
};
console.log(removeFalsyElement(object)) // output should be 2.
The Object.keys method expects an object always. Object.keys 方法总是需要 object。 if we pass null we would get the above mentioned error
如果我们通过 null 我们会得到上述错误
const removeFalsyElement = (object = {}) => {//default value for object in case it is null. Object.keys needs an object always
let sum = 0;
Object.keys(object).forEach(key => {
if (object[key]) {
sum += 1;
}
});
return sum;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.