我有一个组件,它调用 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)
以异步方式进行
componentWillUnmount() {
if (this._root) {
setTimeout(()=> this._root.unmount())
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1716 次 |
| 最近记录: |