【问题标题】:TypeError: Cannot read property 'tagName' of null?TypeError:无法读取 null 的属性“tagName”?
【发布时间】:2021-07-07 06:05:35
【问题描述】:

我正在尝试从 head 标记中动态删除 css 文件。我收到此错误

TypeError:无法读取 null 的属性“tagName”

这是我的代码 https://codesandbox.io/s/lingering-browser-icis7?file=/pages/index.js

export default function IndexPage() {
  useEffect(() => {
    setTimeout(() => {
      document.querySelectorAll('link[rel="stylesheet"]').forEach((item) => {
        let hrefAttr = item.getAttribute("href");
        let splitHref = hrefAttr?.split("/");
        if (splitHref[splitHref?.length - 1]?.startsWith("main")) {
          item.remove();
        }
      }, 2000);
    });
  }, []);
  return (
    <div>
      <Head>
        <link href={`/main.css`} rel="stylesheet" />
      </Head>
      Hello World.{" "}
      <Link href="/about">
        <a className="red">About</a>
      </Link>
    </div>
  );
}

重现错误。:在 setTimeout 函数中更改时间。

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    删除的语法可以更新如下code sandbox

    import Link from "next/link";
    import Head from "next/head";
    import { useEffect } from "react";
    export default function IndexPage() {
      useEffect(() => {
        setTimeout(() => {
          document.querySelectorAll('link[rel="stylesheet"]').forEach((item) => {
            let hrefAttr = item.getAttribute("href");
            let splitHref = hrefAttr?.split("/");
            if (splitHref[splitHref?.length - 1]?.startsWith("main")) {
              console.log("Remove done for ", item);
              item.parentNode.removeChild(item);
            }
          }, 1000);
        });
      }, []);
      return (
        <div>
          <Head>
            <link href={`/main.css`} rel="stylesheet" />
          </Head>
          Hello World.{" "}
          <Link href="/about">
            <a className="red">About</a>
          </Link>
        </div>
      );
    }

    【讨论】:

    • 还是同样的问题
    • 请看截图。如果有错误,请在此处添加错误。
    猜你喜欢
    • 2013-01-28
    • 2020-01-29
    • 2022-01-12
    • 2021-12-04
    • 2021-12-17
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多