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

标签 reactjs react-hooks use-effect use-state event-listener

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/

相关文章:

javascript - "useEffect has a missing dependency"警告有时是错误的吗?

reactjs - Next js api 不适用于 netlify

javascript - 将 React 路由组织成单独的组件

javascript - 与 useState 的异步性质相比,React 的 useReducer 是同步的吗?

javascript - 如何让 React Native ActivityIndi​​cator 在 onPress 之后出现以显示正在加载某些内容?

javascript - react 钩子(Hook)。周期性运行使用效果

reactjs - 如何使 TextInput 中的 selectionColor 属性透明?

javascript - 粘性导航栏-React

javascript - 为什么 useMemo 不起作用?我用错了吗?

javascript - <td> 不能作为 `div` 的 child 出现?