javascript - 无法读取未定义的属性 "replace"

标签 javascript reactjs

enter image description here 在此输入代码 enter image description here 我正在创建一个在线目录,每次单击“更多信息”按钮时,我都会收到 undefined

的 cannot read property replace

我尝试重命名 property 但它仍然无法正常工作

let removeCom = this.props.itemInfo.description.replace("?", "").replace('<td width="110" height="">', "").replace("http://extranet.acetools.com/Catalog/","assets/img/items/").replace((/<INPUT[^>]*>/gmi), "").split('<CENTER><FONT COLOR="RED">', 1);
console.log(removeCom);

最佳答案

这意味着两件事

要么 itemInfo 没有描述,要么你有拼写错误,因为当 javascript 找不到它返回的对象时 undefined 所以你试图访问未定义的替换方法,例如 undefined.replace( )

因此你的代码变成这样

let removeCom = this.props.itemInfo.undefined.replace("?", "").replace('<td width="110" height="">', "").replace("http://extranet.acetools.com/Catalog/","assets/img/items/").replace((/<INPUT[^>]*>/gmi), "").split('<CENTER><FONT COLOR="RED">', 1)
console.log(removeCom);

其他更安全的方法你可以这样做

let { itemInfo } = this.props;
let removeCom;
if(itemInfo.description){
   removeCom  = itemInfo.description.replace("?", "").replace('<td width="110" height="">', "").replace("http://extranet.acetools.com/Catalog/","assets/img/items/").replace((/<INPUT[^>]*>/gmi), "").split('<CENTER><FONT COLOR="RED">', 1)
   console.log(removeCom);

}

关于javascript - 无法读取未定义的属性 "replace",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57380702/

相关文章:

javascript - 转换来自谷歌驱动器的所有 csvs

javascript - Aloha 编辑器 - 在存储库浏览器中连接一个目录

javascript - D3.JS SVG 矩形不出现

javascript - 在 PyCharm 中禁用 React Prop 的自动 {} 插入

css - 在一个方向上对齐和间距 flex

javascript - 使用对象数组中的相同键创建值数组

javascript - react native 路由器通量 : How to style NavDrawer's button and navigation bar?

javascript - ReactJS如何循环遍历数组并获取另一个数组中对象的特定属性

javascript - 幻灯片背景图片 ReactJS | CSS

javascript - 根据数据元素当前拥有的类来更改数据元素的样式?