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. Event handlers are functions that React runs when you perform some action—for example, when you click a button. Even though event handlers are defined inside your component, they don’t run during rendering! So event handlers don’t need to be pure.
If you’ve exhausted all other options and can’t find the right event handler for your side effect, you can still attach it to your returned JSX with a useEffect call in your component. This tells React to execute 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 (Google Map coordinates on a widget) to the current state, useEffect is a good tool. And it can safely over-fire.
关于reactjs - 什么时候应该使用 useEffect 钩子(Hook)而不是事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72273870/