gpt4 book ai didi

reactjs - 什么时候应该使用 useEffect 钩子(Hook)而不是事件监听器?

转载 作者:行者123 更新时间:2023-12-05 02:29:15 27 4
gpt4 key购买 nike

useEffect 钩子(Hook)是否可以使用事件监听器来简化?

例如,在下面的代码片段中,我使用事件监听器来更改一些状态,然后使用 useEffect 钩子(Hook)来响应该状态更改并做一些其他事情

import { useEffect, useState } from "react";

export default function Foo() {
const [isActive, setIsActive] = useState(true);

useEffect(() => {
// do any kind of business logic
}, [isActive]);

return (
<>
<button
type="button"
className="secondary"
onClick={() => setIsActive(true)}
>
ACTIVATE
</button>
<button
type="button"
className="secondary"
onClick={() => setIsActive(false)}
>
DEACTIVATE
</button>
</>
);
}

我应该将 useEffect 逻辑移动到 onClick 监听器吗?

最佳答案

beta 文档建议尽可能在事件处理程序中执行副作用,这里引用自 docs :

In React, side effects usually belong inside event handlers. Eventhandlers are functions that React runs when you perform someaction—for example, when you click a button. Even though eventhandlers are defined inside your component, they don’t run duringrendering! So event handlers don’t need to be pure.

If you’ve exhausted all other options and can’t find the right eventhandler for your side effect, you can still attach it to your returnedJSX with a useEffect call in your component. This tells React toexecute it later, after rendering, when side effects are allowed.However, this approach should be your last resort.

还有 Dan Abramov 的相关引述:

To sum up, if something happens because a user did something,useEffect might not be the best tool.

On the other hand, if an effect merely synchronizes something (GoogleMap coordinates on a widget) to the current state, useEffect is a goodtool. And it can safely over-fire.

关于reactjs - 什么时候应该使用 useEffect 钩子(Hook)而不是事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72273870/

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