如何正确卸载使用createRoot创建的东西?

syd*_*ydd 7 reactjs react-dom

我有一个组件,它调用 React 18createRoot来经常在其中渲染一些内容。我的问题是,如果我尝试删除它,则会unmount触发componentWillUnmount警告:Warning: Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.

如何正确地做到这一点?当我使用 .React 17 时,这段代码没有抛出任何警告ReactDOM.render()。这是一个最小的例子:

import React from "react";
import { createRoot } from "react-dom/client";

class Example extends React.Component {
  componentWillUnmount() {
    if (this._root) {
      // This is causing the warning
      this._root.unmount();
    }
  }
  render() {
    return (
      <div
        ref={(el) => {
          if (el) {
            console.log("creating root");
            this._root = createRoot(el);
            this._root.render(<div>rendered with createRoot</div>);
          }
        }}
      />
    );
  }
}
class Example2 extends React.Component {
  render() {
    // just some code to trigger a re-render
    return (
      <div>
        {this.state?.aa ? <div>bbb</div> : <Example />}
        <button onClick={() => this.setState({ aa: true })}>click me</button>
      </div>
    );
  }
}
createRoot(document.getElementById("app")).render(<Example2 />);
Run Code Online (Sandbox Code Playgroud)

代码沙盒链接

Shi*_*ain 3

以异步方式进行

componentWillUnmount() {
    if (this._root) {
     
      setTimeout(()=> this._root.unmount())
  
    }
  }
Run Code Online (Sandbox Code Playgroud)