首页 > 解决方案 > Nextjs:在卸载组件时删除元素

问题描述

知道如何在 componentwillunmount 上的 nextjs 中从 dom 中删除一个元素吗?我正在使用 Head 组件加载在页面上生成元素的 JS 脚本。当我导航到另一个页面时,该元素仍然存在,因此我需要将其删除。我想过使用componentwillunmount和document.getelementbyclassname,但由于某种原因它在nextjs中不起作用。

关于如何解决它的任何想法?

这不会做任何事情,即使按钮被拾起:

 componentDidMount() {
    oldButton2 = document.getElementsByClassName("button");
  }
  componentWillUnmount() {
    if (oldButton2.parentNode) {
      oldButton2.parentNode.removeChild(oldButton2);
    }
  }

标签: next.js

解决方案


推荐阅读