错误类型:TypeError(类型错误),无法读取null的replace属性。

3
我遇到了一个 TypeError 的问题,虽然我的应用程序仍在正常运行。

"ERROR TypeError: Cannot read property 'replace' of null"

如何解决这个问题? 请参考下图:enter image description here
if (isInitial) {

                  // Add Data Rows (initially)
                  for(const row of rows) {

                    const clientVisitGuid = row[2];
                    const location = row[3];

                    row[5] = row[5].replace(/\//g, '\/\u200B');
                    const service = row[5];

                    const rowId = `${service || 'zzz'}_${location}_${clientVisitGuid}`;
                    const sortString = `${service || 'zzz'}_${location}_${clientVisitGuid}`;
                    const daysPastDischarge = parseInt(row[6]);
                    const isMarked = parseInt(row[7]) === 1 ? true : false;

                    if (cbt.hasBodyRow(rowId) === false) {

                      const values: Array<[string, string | number]> = [];
                      let isAllClear = true;
                      for(let i = 0; i < row.length; i++) {
                        const colId: string = cbt.headerRow.headerCols[i].id;
                        const colVal: string | number = row[i];
                        if (cbt.headerRow.headerCols[i].isFlag === true && colVal !== 1) {
                          isAllClear = false;
                        }
                        values.push([colId, colVal]);
                      }

                      const valueHash = hash(JSON.stringify(row));

                      cbt.addBodyRow(
                        rowId,
                        values,
                        valueHash,
                        sortString,
                        daysPastDischarge,
                        isMarked,
                        isAllClear,
                        true,
                      );
                    }
                  }

1
在我们能够帮助您之前,我们需要知道"rows"是什么意思。 - undefined
没有看到行中包含什么内容,很难知道发生了什么。我猜测在某个时候row[5]是空的,因此引发了这个错误。您可以更新代码,在运行其余部分之前检查值是否为空,然后根据您的用例以合理的方式进行反应(不执行剩余的代码、提供默认值,或者只是使用null运行剩余的代码但不尝试替换字符)。 - undefined
2个回答

6

要修复错误,您需要在尝试替换字符串之前检查变量是否存在。像这样用if语句包装它:

if(row[5]) {
    row[5] = row[5].replace(/\//g, '\/\u200B');
    const service = row[5];
}

2

看起来row[5]为空。你应该先检查row[5]是否存在。可以像这样:

似乎row[5]是空的。您应该首先检查row[5]是否存在。类似于

if(row[5]) {
     row[5] = row[5].replace(/\//g, '\/\u200B');
     const service = row[5];
} 

你还应该考虑在值为空时添加一些事件处理。最初的回答中未提及此事。请注意,保留HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接