很久很久以前,我们在类中使用了 React,还记得吗?
当时,我们有了生命周期方法的概念,即接受在特定时刻执行的回调的类上的方法。三巨头:装载时、更新时和卸载时。
这很重要,在类组件上,返回的 JSX 是在 render 方法上生成的,状态附加到组件的 this 上,并且应用程序开发人员需要一种方法来知道在某些时刻执行操作。我们对组件生命周期的时间有了概念:
当然,您有一个重要的 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.
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:
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:
후크와 반응형 모델은 React가 브라우저에서 자체적으로 분리되도록 하여 앱 코드가 화면 렌더링 프로세스의 어느 순간에 있는지에 대해 덜 신경쓰게 만듭니다. 더 이상 자신의 규칙에 따라 업데이트를 강요하거나 메모를 처리하지 않아도 됩니다. 이는 앱 개발자에게는 덜 직접적이지만 모델 측면에서는 더 직접적입니다.
각 재렌더링은 구조를 생성하고 React가 나머지를 처리합니다.
以上是带钩子的 React 中不存在生命周期的详细内容。更多信息请关注PHP中文网其他相关文章!