为 JSX 元素而不是组件记录卸载
logging unmount for JSX element instead of components
我们如何观察 JSX 元素是否挂载。例如,我有一个带有 useEffect
的简单组件。它在我的 App.js
里面 我可以安装和卸载我的组件,如果安装或卸载,该组件内部的 useEffect
将记录。
但我想知道是否有办法使用 JSX 元素。例如,我们可以在不创建组件的情况下为 App.js
内的 h2
标记实现它吗?
App.js
import React, { useState } from "react";
import "./App.css";
import Mycomponent from "./Mycomponent";
const App = () => {
const [mount, setMount] = useState(true);
return (
<div>
<b>Mounting and Unmounting</b>
<button
onClick={() => {
setMount(!mount);
}}
>
{mount ? "click to unmount" : "click to mount"}
</button>
{mount && <Mycomponent />}
</div>
);
};
export default App;
Mycomponent.js :
import React, { useEffect } from "react";
const Mycomponent = () => {
useEffect(() => {
console.log("mounted");
return () => {
console.log("unmounted");
};
}, []);
return (
<div>
<h1>component mounted</h1>
</div>
);
};
export default Mycomponent;
我认为你可以为此使用回调引用:
export default function App() {
const [counter, setCounter] = React.useState(0);
const measuredRef = (node) => {
if (node == null) {
console.log('I was removed');
} else {
console.log('I was mounted');
}
};
return (
<div
onClick={() => {
setCounter(counter + 1);
}}
>
{counter % 2 == 0 && <h1 ref={measuredRef}>Hello, world</h1>}
<p>Start editing to see some magic happen :)</p>
</div>
);
}
文档中有一些相关的 example:
In this example, the callback ref will be called only when the
component mounts and unmounts, since the rendered <h1>
component stays
present throughout any rerenders.
我们如何观察 JSX 元素是否挂载。例如,我有一个带有 useEffect
的简单组件。它在我的 App.js
里面 我可以安装和卸载我的组件,如果安装或卸载,该组件内部的 useEffect
将记录。
但我想知道是否有办法使用 JSX 元素。例如,我们可以在不创建组件的情况下为 App.js
内的 h2
标记实现它吗?
App.js
import React, { useState } from "react";
import "./App.css";
import Mycomponent from "./Mycomponent";
const App = () => {
const [mount, setMount] = useState(true);
return (
<div>
<b>Mounting and Unmounting</b>
<button
onClick={() => {
setMount(!mount);
}}
>
{mount ? "click to unmount" : "click to mount"}
</button>
{mount && <Mycomponent />}
</div>
);
};
export default App;
Mycomponent.js :
import React, { useEffect } from "react";
const Mycomponent = () => {
useEffect(() => {
console.log("mounted");
return () => {
console.log("unmounted");
};
}, []);
return (
<div>
<h1>component mounted</h1>
</div>
);
};
export default Mycomponent;
我认为你可以为此使用回调引用:
export default function App() {
const [counter, setCounter] = React.useState(0);
const measuredRef = (node) => {
if (node == null) {
console.log('I was removed');
} else {
console.log('I was mounted');
}
};
return (
<div
onClick={() => {
setCounter(counter + 1);
}}
>
{counter % 2 == 0 && <h1 ref={measuredRef}>Hello, world</h1>}
<p>Start editing to see some magic happen :)</p>
</div>
);
}
文档中有一些相关的 example:
In this example, the callback ref will be called only when the component mounts and unmounts, since the rendered
<h1>
component stays present throughout any rerenders.