react銷毀方法鉤子0
Updated: With React 16.8, React Hooks are available in a stable release!
更新:隨著React 16.8的發布, React Hooks已經發布!
Outdated: Hooks are still an experimental proposal. They’re currently in React v16.7.0-alpha
過時的:掛鉤仍然是一個實驗性的建議。 他們目前在React v16.7.0-alpha中
TL;DR In this article we will attempt to understand what are React Hooks and how to use them for our good. We will implement different examples and see the differences (gains) Hooks bring to us. If you want to skip the reading, here you can find shorter version in a few slides. And here ? you may get the examples and try them yourself.
TL; DR在本文中,我們將嘗試了解什么是React Hooks以及如何將它們用于我們的利益。 我們將實現不同的示例,并查看Hooks帶給我們的差異(收益)。 如果你想跳過讀取, 在這里你可以找到幾張幻燈片較短的版本。 在這里 ? 您可以獲取示例并自己嘗試。
什么是React Hooks ? (What are React Hooks?)
Simple functions for hooking into the React state and lifecycle features from function components.
用于從功能組件連接到React狀態和生命周期功能的簡單函數。
What this means is that hooks allow us to easily manipulate our function component’s state without needing to convert them into class components. This saves us from having to deal with all the boilerplate code involved.
這意味著鉤子使我們能夠輕松操縱函數組件的狀態,而無需將其轉換為類組件。 這使我們不必處理所有涉及的樣板代碼。
Hooks don’t work inside classes — they let you use React without classes. And also, by using them, we can totally avoid using lifecycle methods, such as componentDidMount, componentDidUpdate, etc. Instead, we will use built-in hooks like useEffect, useMutationEffect or useLayoutEffect. We will see how in a moment.
掛鉤在類內部不起作用-它們使您可以在沒有類的情況下使用React。 而且,通過使用它們,我們可以完全避免使用生命周期方法,例如componentDidMount , componentDidUpdate等。相反,我們將使用諸如useEffect , useMutationEffect或useLayoutEffect之類的內置掛鉤。 一會兒我們將看到。
Hooks are JavaScript functions, but they impose two additional rules:
掛鉤是JavaScript函數,但是它們施加了兩個附加規則 :
?? Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
Only?僅在頂層調用Hooks。 不要在循環,條件或嵌套函數中調用Hook。
?? Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. There is just one other valid place to call Hooks — your own custom Hooks. We’ll see them later in this article.
Only? 僅從React函數組件調用Hooks。 不要從常規JavaScript函數調用Hook。 還有另外一個有效的地方可以稱為掛鉤-您自己的自定義掛鉤。 我們將在本文后面看到它們。
他們為什么是好東西? (Why are they good thing?)
? Reusing logicUp until now, if we wanted to reuse some logic in React, we had two options: higher-order components or render props. With React Hooks we have an alternative, that comes with a much easier to understand (in my personal opinion!) syntax and logic flow.
? 重用邏輯到現在為止,如果我們想重用React中的某些邏輯,我們有兩個選擇: 高階組件或渲染 道具。 有了React Hooks,我們有了另一種選擇,它具有更容易理解的語法和邏輯流程(以我個人的觀點!)。
? Giant componentsBy avoiding the boilerplate code we need to write when using classes or by removing the need for multiple nesting levels (which could come when using render props), React Hooks solve the issue of having giants components (that are really hard to maintain and debug).
? 大型組件通過避免使用類時需要編寫的樣板代碼或消除對多個嵌套級別的需求(使用渲染道具時可能會出現),React Hooks解決了具有巨型組件的問題(實際上很難維護)并進行調試)。
? Confusing classesAgain, allowing us NOT to use classes or class components in our applications makes the developers’s (especially beginner’s) life easier. This is because we don’t have to use the ‘this’ keyword and we don’t need to have the understanding of how bindings and scopes work in React (and JavaScript).
? ?onfusing類再次,讓我們不使用類或類組件在我們的應用使得開發商的(尤其是初學者),生活更輕松。 這是因為我們不必使用'this'關鍵字,也不需要了解在React(和JavaScript)中綁定和作用域是如何工作的。
This is NOT to say that we (the developers) don’t have to learn these concepts — on the contrary we must be aware of them. But in this case, when using React hooks, our worries are one fewer ?.
這并不是說我們(開發人員)不必學習這些概念,相反,我們必須意識到它們。 但是在這種情況下,當使用React鉤子時,我們的擔心少了一個?
So, after pointing out what issues the hooks solve, when would we use them?
那么,在指出了鉤子解決了什么問題之后,我們什么時候才能使用它們呢?
If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that in the next examples.
如果編寫函數組件并意識到需要向其添加一些狀態,則以前必須將其轉換為類。 現在,您可以在現有功能組件中使用掛鉤。 在下面的示例中,我們將進行此操作。
如何使用React Hooks ? (How to use React Hooks?)
React Hooks come to us as built-in ones and custom ones. The later are the ones we can use for sharing logic across multiple React components.
React Hooks是內置的和自定義的 。 后者是我們可用于在多個React組件之間共享邏輯的組件。
As we’ve already learned, hooks are simple JavaScript functions, which means we will be writing just that, but in the context of React function components. Previously these components were called stateless, a term that is not valid anymore, as hooks give us a way to use the state in such components ?.
正如我們已經了解到的那樣,鉤子是簡單JavaScript函數,這意味著我們將僅在React 函數組件的上下文中編寫該函數 。 以前,這些組件稱為無狀態 ,該術語不再有效,因為鉤子提供了一種在此類組件中使用狀態的方法。
An important thing to remember is that we can use both built-in and custom hooks multiple times in our components. We just have to follow the rules of hooks.
要記住的重要一點是,我們可以在組件中多次使用內置和自定義鉤子。 我們只需要遵循鉤子規則即可 。
The following examples try to illustrate that.
以下示例試圖說明這一點。
基本的內置掛鉤 (Basic built-in hooks)
useState hook — returns a stateful value and a function to update it.
useState hook —返回一個有狀態的值和一個更新它的函數。
useEffect hook — accepts a function that contains imperative, possibly effectful code (for example fetching data or subscribing to a service). This hook could return a function that is being executed every time before the effect runs and when the component is unmounted — to clean up from the last run.
useEffect掛鉤—接受一個包含命令性的,可能有效的代碼的函數(例如,獲取數據或預訂服務)。 每次運行效果之前和卸載組件時,此掛鉤都可以返回正在執行的函數,以從上一次運行中清除。
useContext hook — accepts a context object and returns the current context value, as given by the nearest context provider for the given context.
useContext hook —接受上下文對象,并返回當前上下文值,該值由最近的上下文提供者為給定上下文提供。
定制掛鉤 (Custom hooks)
A custom Hook is a JavaScript function whose name starts with “use
” and that may call other Hooks. For example, useFriendName below is our first custom Hook:
自定義掛鉤是一個JavaScript函數,其名稱以“ use
”開頭,并且可以調用其他掛鉤。 例如,下面的useFriendName是我們的第一個自定義Hook:
export default function useFriendName(friendName) {const [isPresent, setIsPresent] = useState(false);useEffect(() => {const data = MockedApi.fetchData();data.then((res) => {res.forEach((e) => {if (e.name === friendName) {setIsPresent(true);}});});});return isPresent;
}
Building your own custom hooks lets you extract component logic into reusable functions. This could be your application’s shared functionality that you can import everywhere you need it. And also, we must not forget, that our custom hooks are the other allowed (see the rules) places to call built-in hooks.
構建自己的自定義掛鉤可以使您將組件邏輯提取到可重用的函數中。 這可能是您應用程序的共享功能,您可以將其導入所需的任何位置。 而且,我們也不要忘記,自定義鉤子是調用內置鉤子的另一個允許的位置( 請參閱規則 )。
結論 (Conclusion)
React Hooks are not really a new feature that popped out just now. They are another (better ?) way of doing React components that need to have state and/or lifecycle methods. Actually, they use the same internal logic that is being used currently by the class components. To use them or not — this is the question to which the future will give the best answer.
React Hooks并不是剛剛出現的新功能。 它們是需要狀態和/或生命周期方法的另一種(更好的)React組件。 實際上,它們使用與類組件當前正在使用的相同的內部邏輯。 是否使用它們-這是未來將給出最佳答案的問題。
My personal opinion? That this is going to be the future of any React development that involves state and lifecycle usage.
我個人的意見? 這將是任何涉及狀態和生命周期使用的React開發的未來。
Let’s see how the community will react to the proposal ? and hopefully we will see them polished and fully functioning in the next React releases. ?
讓我們看看社區將對該提案有何React? 希望我們在下一個React版本中能看到它們的完善和功能。 ?
? Thanks for reading! ?
? 謝謝閱讀! ?
參考文獻 (References)
Here you may find the links to the resources I found useful when writing this article:
在這里,您可能會找到指向我在撰寫本文時有用的資源的鏈接:
https://github.com/mihailgaberov/react-hooks/ — link to GitHub repo with the examples and presentation.
https://github.com/mihailgaberov/react-hooks/ —通過示例和演示文稿鏈接到GitHub存儲庫。
https://mihailgaberov.github.io/react-hooks/ — link to presentation slides.
https://mihailgaberov.github.io/react-hooks/-鏈接到演示幻燈片。
https://reactjs.org/docs/hooks-intro.html — official ReactJS blog.
https://reactjs.org/docs/hooks-intro.html-ReactJS官方博客。
https://youtu.be/dpw9EHDh2bM — Introduction to Hooks, React Conf 2018
https://youtu.be/dpw9EHDh2bM-Hooks簡介,React Conf 2018
https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 — An explanatory article by Dan Abramov.
https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889-Dan Abramov的說明性文章。
https://daveceddia.com/useeffect-hook-examples/ — A very useful article explaining different use cases of useEffect hook.
https://daveceddia.com/useeffect-hook-examples/ —一篇非常有用的文章,介紹了useEffect鉤子的不同用例。
https://ppxnl191zx.codesandbox.io/ — An example of a React animation library experimenting with Hooks.
https://ppxnl191zx.codesandbox.io/ —一個使用Hooks進行實驗的React動畫庫的示例。
https://dev.to/oieduardorabelo/react-hooks-how-to-create-and-update-contextprovider-1f68 — A nice and short article showing how to create and update context provider with React Hooks.
https://dev.to/oieduardorabelo/react-hooks-how-to-create-and-update-contextprovider-1f68 —一篇不錯的簡短文章,展示了如何使用React Hooks創建和更新上下文提供程序。
翻譯自: https://www.freecodecamp.org/news/hooking-with-react-hooks-964df4b23960/
react銷毀方法鉤子0