解决React卸载组件发生的问题(root.unmount())

在React18中,创建根节点应使用createRoot,而更新根节点则需调用root.render()。文章指出,错误地再次调用createRoot会导致警告。解决方法是暴露入口文件的root实例并使用root.unmount()来卸载组件。
摘要由CSDN通过智能技术生成

 前言

报错内容:

Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.

报错原因: 您正在对之前已传递给createRoot()的容器调用ReactDOMClient.createRoot如果您想更新现有的根,请对其调用root.render()。然而,错上加错。

补充

1. 在React18中,创建根节点用createRoot

import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById("root"))

2. 删除节点 unmountComponentAtNode(),在React18中被root.unmount()所取代。

原先的代码

import React, { useState, useEffect } from "react"
import "./index.css"

import { createRoot } from "react-dom/client"
export default function Hook() {
 
  const [count, setCount] = useState(0)
  const [name, setName] = useState("tom")

  useEffect(() => {
    let timer = setInterval(() => {
      setCount((count) => count + 1)
    }, 1000)

    return () => {
      clearInterval(timer)
    }
  }, [])
  function add() {
    setCount(count + 1)
    // setCount((count) => count + 1)
  }
  function changeName() {
    setName("丽丽")
  }
  function unmount() {
    const root = createRoot(document.getElementById("root"))
    root.unmount()
  }
  return (
    <div>
      <h2>setState的两种写法</h2>
      <h3>我的名字是:{name}</h3>
      <p>{count}</p>
      <button onClick={add}>+1</button>
      <button onClick={changeName}>换名字</button>
      <button onClick={unmount}>卸载</button>
    </div>
  )
}

解决办法

1.  暴露入口文件的root

export const root = createRoot(document.getElementById("root"))

2.  组件文件中调用及使用 root.unmount()删除即可

import { root } from "../../index"
function unmount() {
  root.unmount()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

才不吃胡萝卜嘞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值