gpt4 book ai didi

reactjs - 我应该使用 useEffect() 进行 dom 操作还是直接进行操作?

转载 作者:行者123 更新时间:2023-12-03 09:27:24 30 4
gpt4 key购买 nike

React docs I see this piece of code :

function Example() {
const [count, setCount] = useState(0);

//THE SUBJECT OF MY QUESTION:
useEffect(() => {
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

所以,我的问题是为什么不使用 useEffect 更改 document.title 或任何其他 DOM,如下所示:
function Example() {
const [count, setCount] = useState(0);

//THE SUBJECT OF MY QUESTION:
document.title = `You clicked ${count} times`;

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

我知道,例如发送请求时,它是异步的,我们需要在 useEffect 中进行。但是 DOM 操作不是异步的,它花费的时间相对为 0,为什么我们还要使用 useEffect 钩子(Hook)呢?

最佳答案

几乎 一样,看我的相关回答,useEffect in-depth .

不同之处在于一个显着的“陷阱”,useEffect回调执行 after the render phase .

const App = () => {
useEffect(() => {
console.log("executed after render phase");
});

console.log("executed at render phase");

return <></>;
};

将导致:
executed at render phase
executed after render phase

Edit useEffect execute phase

关于reactjs - 我应该使用 useEffect() 进行 dom 操作还是直接进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62061679/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com