简体   繁体   English

TypeError:无法在反应中读取 null 的属性“0”

[英]TypeError: Cannot read property '0' of null in react

I've got a typescript app that I've been asked to help with.我有一个 typescript 应用程序,有人要求我提供帮助。 At the last minute the website owner wanted to change the front end so the links are clickable.在最后一刻,网站所有者想要更改前端,以便可以点击链接。 Only issue is they data is entered in the backend as a normal anchor href tag.唯一的问题是他们的数据作为普通的锚href标签输入到后端。 So I've been working on a work around because i can't use that innerhtml method for security reasons.所以我一直在努力解决,因为出于安全原因我不能使用该 innerhtml 方法。

  switch (note.kind) {
    case "text":
      return (
        <div>
          {" "}
          {note.text.map((content: string, idx: number) => {
            const result = [];
            const matches = content.match(
              /(.*?)(<a href=")?(https?|www)((".*?>.*?<\/a>)|[^\s>]?)*(.*?)/gi
            );

            if (!!matches) {
              matches.forEach((match) => {
                let link;
                if (/href="/i.test(match)) {
                  const url = match
                    .match(/<a href="(.*?)(?=">)/i)![0]
                    .replace('<a href="', "");
                  const linkText = match
                    .match(/(?:<a href=".*?">)(.*)(?=<\/a>)/)![0]
                    .replace(/(?:<a href=".*?">)/i, "");
                  link = <a href={url}>{linkText}</a>;
                } else {
                  const url = match.match(/(https?|www)[^\s]*/gi)!.join("");
                  link = <a href={url}>{url}</a>;
                }

                const splitter = match.match(
                  /(<a href=")?(https?|www)[^\s]*(.*<\/a>)?/gi
                )![0];
                const paredPlainText = match.split(new RegExp(splitter));
                result.push(paredPlainText[0]);
                result.push(link);
                result.push(paredPlainText[1]);
              });
            } else {
              result.push(content);
            }
            console.log(result);

            return <p>{result}</p>;
          })}
        </div>
      );

This is my code but the only issue is I'm running into TypeError: Cannot read property '0' of null on the.match methods.这是我的代码,但唯一的问题是我遇到了 TypeError: Cannot read property '0' of null on the.match 方法。 Any help would be much appreciated Thank you!任何帮助将不胜感激谢谢!

You should make sure there was a match from regex and it isn't null您应该确保正则表达式匹配并且不是 null

const splitter = match.match(/(<a href=")?(https?|www)[^\s]*(.*<\/a>)?/gi);

if (splitter && splitter.length) {
    const paredPlainText = match.split(new RegExp(splitter[0]));
    const [firstParedPlainText, secondParsedPlainText] = paredPlainText || [null, null];
    if (firstParedPlainText) result.push(firstParedPlainText);

    result.push(link);
    if (secondParsedPlainText) result.push(secondParsedPlainText);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM