首页 > web前端 > js教程 > 正文

带钩子的 React 中不存在生命周期

DDD
发布: 2024-11-14 15:18:02
原创
836 人浏览过

Lifecycle doesn

很久很久以前,我们在类中使用了 React,还记得吗?

当时,我们有了生命周期方法的概念,即接受在特定时刻执行的回调的类上的方法。三巨头:装载时、更新时和卸载时。

古老但黄金的课程

这很重要,在类组件上,返回的 JSX 是在 render 方法上生成的,状态附加到组件的 this 上,并且应用程序开发人员需要一种方法来知道在某些时刻执行操作。我们对组件生命周期的时间有了概念:

  • componentDidMount 是组件首次渲染并向 DOM 添加元素的时刻,也是开始连接和 API 请求等副作用的时刻。
  • shouldComponentUpdate 允许您手动设置逻辑来比较下一个 props 和状态,并返回一个布尔值来定义是否可以跳过重新渲染。
  • componentDidUpdate 是状态或 props 更改的时刻,再次调用 render 方法并对身份差异进行协调更改并应用于 DOM,有助于将状态与新 props 同步并执行逻辑操作。
  • componentWillUnmount 是 React 将从 DOM 中删除元素的时候,是清理内容和避免内存泄漏的好地方。

当然,您有一个重要的 API,例如forceUpdate,如果您使用的外部数据无法与 React 状态更新连接,它允许您手动触发重新渲染

在概念层面上,我们有一种更直接的方式来执行应用程序的流程。生命周期方法遵循 DOM 元素的类似生命周期,您可以自己执行 memo 和 forceUpdates,同步状态是执行逻辑的默认方式。

这种直接性被认为是简单的,与反应式模型相比,学习这些概念更容易。但后来,Hooks 出现并改变了一切。

未命名的反应性

过渡过程令人困惑。首先,为了让开发变得简单,并在某种程度上维护开发人员所拥有的 React 模型的概念愿景,许多交流试图展示 hooks 模型的相似之处。为了拥有 3 个主要的生命周期方法,他们展示了 useEffect 的解决方法。

// componentDidMount
 useEffect(() => {
    // code...

    // componentWillUnmount:
    return function cleanup() {
      // code...
    };
  }, []);

// componentDidUpdate
 useEffect(() => {
    // code...

  }, [dependencyState, dependencyProp]);
登录后复制

所以,大多数用 hooks 编写的新 React 代码都遵循这个想法,开始同步状态是一个自然的过程。为了保持生命周期方法的相同理念,这是调用 setState 并触发重新渲染过程的地方。

有什么问题吗?

同步状态成为问题,useEffect 的错误使用成为问题,双重重新渲染成为问题,太多重新渲染成为问题,性能成为问题。

It’s a little bit confusing this step from React, at least for me. Because, the move to hooks was a move to a reactive model, even if it’s a coarse-grained one. But the communication was that nothing really big changed. No content about the reactivity concepts and theory, even working for years with React, I just started to really understand reactivity reading Ryan Carniato’s blog posts about reactivity and solid.

Even knowing that useEffect had a misuse, I really didn’t understand why, and this lack of conceptual theory about reactivity makes committing mistakes with hooks so easy. useEffect became the most hated hook, being called “useFootgun” for some people. The point is, there is a conceptual confusion in React that expresses itself as all the issues with useEffect we see today.

useEffect issues are not the cause of the problem, but the consequence.

What about life cycle with hooks

So, this is the thing. There is no life cycle in the concept of reactivity.

You have a change, you react to it deriving and doing side effects. Effects are the consequence, not the cause. There is no state sync and no concepts of mount and unmount.

It should not matter if it is the first, the 10th or the last render before unmount, and the hooks don’t care for it, by the way, even useEffect.

Try it:

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

  useEffect(() => {
    console.log('effect', count);

    return () => {
      console.log('clean up', count);
    }
  }, [count]);

  return (
    <button onClick={() => setCount((state) => state + 1)}>
      {count}
    </button>
  )
}
登录后复制

You will see on your console both functions being executed on each state update. First the clean up one, and then the effect callback. If you are using useEffect with some state or prop to do a subscription, every time the dependencies changes, the clean up function will be called, and then the new callback, doing the subscription again, but with the new values.

You should look your app code as the React model simplified:

UI = fn(state)
登录后复制

If you have a component like this one:

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

  return (
    <button onClick={() => setCount((state) => state + 1)}>
      {count}
    </button>
  )
}
登录后复制

what you really have, when you click on the button and adds +1 to the count, conceptually, is something like this:

// first render
<button>0</button> = fn({ count: 0 });
// button click - re-render
<button>1</button> = fn({ count: 1 });
// button click - re-render
<button>2</button> = fn({ count: 2 });
// button click - re-render
<button>3</button> = fn({ count: 3 });
登录后复制

Each click calls again the fn, with a new state, generating a new version of UI. The state should change by the action of the user or by an async value that should be made with async derivations.

This way you keep the clean idea:

  • state transitions make a new fn call
  • with the new state, you get the UI description
  • if it’s different, update the screen.

A clean and consistent model.

it’s a matter of the renderer to care with adding, updating and removing elements from the screen. At the component level, what matters is:

  • 상태가 변경된 경우
  • 앱이 사용자 작업을 처리할 수 있는지
  • JSX에서 반환된 구조

후크와 반응형 모델은 React가 브라우저에서 자체적으로 분리되도록 하여 앱 코드가 화면 렌더링 프로세스의 어느 순간에 있는지에 대해 덜 신경쓰게 만듭니다. 더 이상 자신의 규칙에 따라 업데이트를 강요하거나 메모를 처리하지 않아도 됩니다. 이는 앱 개발자에게는 덜 직접적이지만 모델 측면에서는 더 직접적입니다.

각 재렌더링은 구조를 생성하고 React가 나머지를 처리합니다.

以上是带钩子的 React 中不存在生命周期的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板