我开始了我自己的 React JS 之旅,作为我的入门 Pokemon 来探索 Javascript 框架世界。乍一看,我爱上了它,因为它减少了大量命令式 DOM 操作代码。我真的很喜欢框架根据状态自动操作 DOM 的想法。
一开始,我没有考虑 React 的大小和它消耗的内存,这可以在重量上击败 Snorlax。
学习 React 后,我接触到了很多框架,比如 Vue、Angular、Svelte。当我终于接触到 SolidJS 时,我的眼睛睁开了
我开始关注 SolidJS 的作者 Ryan Carniato 的直播和文章。他完全改变了我看待框架的方式。我开始了解 Javascript 框架的反应系统。当我回头看到 My Starter Pokemon React 及其反应性和渲染系统时,我无法控制自己的笑
好像我从一开始就被愚弄了。为什么每当状态发生变化时都需要重新运行一切?如果是这样那么为什么我们真的需要一个名为 useEffect 的钩子来充当副作用。
我将这篇文章命名为 React 中的 useEffect 实际上是一个 Effect 吗?就像Vegapunk 睁开了人们关于政府的眼睛(抱歉剧透了 OP 粉丝) 一样,让你对 React 睁开眼睛。对此有很多值得批评的想法。所以今天是使用Effect的日子,他隐藏了自己的真名,撒谎最多。
如果你是初学者或者你问一些 React 初学者,他们会对 useEffect 的解释为
只要依赖数组中的值发生变化就会重新运行的函数。
如果你是那个人,你真的很幸运知道你被教导是错误的真相。每当发生变化时,React 就会重新运行,所以不需要重新运行函数,因为不需要它。下面我就来解释一下真相
让我解释一下效果的真正含义。在Reactivity系统中,Effect实际上被称为Side Effect。让我们从一个例子开始
const name = "John Doe" createEffect(()=>{ console.log("New name", name) },[name])
此处 createEffect 函数接受一个函数,只要第二个参数中的 Array 中的值发生变化,该函数就会重新运行。 createEffect 中的函数是名称的副作用,换句话说,该函数取决于状态名称。每当名称的值更改时,副作用就会重新运行。这就是副作用真正的含义。
让我用 React 编写相同的代码
const [name, setName] = useState("John Doe") useEffect(()=>{ console.log("New name", name) },[name]) setName("Jane Doe")
每当调用 setName 时,useEffect 都会重新运行。我完全明白了。让我通过简单地删除 useEffect 来给出等效代码。它也有效,因为 React 的 useState 不会创建任何反应状态
const [name, setName] = useState("John Doe") console.log("New name", name) setName("Jane Doe")
TADA! 它在 React 中工作得很好,因为每当 useState 的状态时它都会重新运行
变化。我再举一个例子来解释一下useEffect。
const [name, setName] = useState("John Doe") const [age, setAge] = useState(18) console.log("New name", name) setAge(21)
现在每当年龄改变时,console.log("New name", name)也会被执行,这不是我们想要的。所以我们用 useEffect 包装它。
const [name, setName] = useState("John Doe") const [age, setAge] = useState(18) useEffect(()=>{ console.log("New name", name) },[name]) setName("Jane Doe")
现已修复。因此,useEffect 实际上是阻止执行,这与 Effects 完全相反。我希望你明白它的真正作用。这里有 useEffect 的正确解释。
useEffect 是一个钩子,仅当状态发生变化时才执行
我知道副作用的解释是类似的,但它就像硬币的反面。
副作用解释
副作用是每当状态发生变化时执行的函数
在反应系统中,除了Effects重新运行之外没有什么,Effects是只在状态改变时运行的函数。
在React中,除了Effects重新运行之外的所有内容,Effects都是在依赖数组没有变化的情况下阻止执行的函数
最后我希望您了解 useEffect 的真正用途。上面的例子被描述为“你可能不需要效果的最差实践”。我完全明白了。但这就像他们建议我们不要使用 useEffect 作为 Effect。
解释为
useEffect 是一个 React Hook,可让您将组件与外部系统同步。
I can't totally get it because The Phrase synchronize with external system means
The system's internal state is updated to match the state of the external system.
But in reality, useEffect had nothing to do with that. useSyncExternalStore does works in problem with some quirks ( Really this problem can't be solved 100%. For now , save that for My Another article ).
Just think about this facts that React reruns code whenever state changes and useEffect is commonly used along with React state, Then Why do we need to run something based on a state? because always reruns whenever something changes.
I found a page named as Synchronizing with Effects at React Official Docs which explains about it . At there, They explained that as
Effects let you run some code after rendering so that you can synchronize your component with some system outside of React.
From above lines, It is clear that useEffect lets you write a function which executes after rendering of React. Then WTF it is named as useEffect? Does this had any kind of connection with Effect as it's name implies? It's more similar to window.onload of DOM API.
I still can't digest the example they gave
import { useState, useRef, useEffect } from 'react'; function VideoPlayer({ src, isPlaying }) { const ref = useRef(null); if (isPlaying) { ref.current.play(); // Calling these while rendering isn't allowed. } else { ref.current.pause(); // Also, this crashes. } return <video ref={ref} src={src} loop playsInline />; } export default function App() { const [isPlaying, setIsPlaying] = useState(false); return ( <> <button onClick={() => setIsPlaying(!isPlaying)}> {isPlaying ? 'Pause' : 'Play'} </button> <VideoPlayer isPlaying={isPlaying} src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" /> </> ); }
Here is the reason the error If You try to run it
Runtime Error App.js: Cannot read properties of null (reading 'pause') (9:16) 6 | if (isPlaying) { 7 | ref.current.play(); // Calling these while rendering isn't allowed. 8 | } else { > 9 | ref.current.pause(); // Also, this crashes. ^ 10 | } 11 | 12 | return <video ref={ref} src={src} loop playsInline />;
They told to us wrap it inside useEffect to solve this by
useEffect(() => { if (isPlaying) { ref.current.play(); } else { ref.current.pause(); } });
because ref.current is set to null before rendering. But I could solve this by simply changed it to
if (isPlaying) { ref.current?.play(); } else { ref.current?.pause(); }
If It's that what they willing to do, They it should be named as onMount like Vuejs not useEffect because effects at other library like VueJS, SolidJS really does side effect.
Here is the explanation They connected the above example with synchronisation
In this example, The “external system” you synchronized to React state was the browser media API
Does that really make any sense? I still don't know Why used synchronized here?. Here Browser Media API is available after First Render So Then Why there is a necessary of Effect here? It's a Sick Example for Effect. I never thought They would explain Effect with Example Code.
Effects let you specify side effects that are caused by rendering itself, rather than by a particular event.
It found this under the title What are Effects and how are they different from events? and gave above example code for this. After understanding What React really does in name of Effect and reading My Explanation, Could you connect anything?. They gave explanation of Effect of Reactivity System But They did exactly opposite. This is what I always wanted to express to Others
I hope You understand What does Effect means? and What React does in name of Effect?. After thinking All this shits, I finally decided to call useEffect
as usePreventExecution. I knew that name given by me is sick ;-) . But It is nothing when compares to What They stated about it at Official Documentation. If You found any other suitable name, Let me know at Comments.
以上是React 中的 useEffect 实际上是一个 Effect 吗?的详细内容。更多信息请关注PHP中文网其他相关文章!