react 生命掛鉤
In this blog post, we are going to learn -
在這篇博客中,我們將學習-
- What React hooks are 什么是React鉤子
- How to use hooks for state management 如何使用掛鉤進行狀態管理
Before we start working with hooks, let us take a brief moment to talk about state management.
在開始使用鉤子之前,讓我們花一點時間討論狀態管理。
State management is managing data that flows between our application components. It could be data flowing inside one component (local state) or data flowing between multiple components (shared state). We need to manage state because sometimes components need to talk to each other through a reliable source of information. In Redux, this reliable source of information is called the store.
狀態管理正在管理在我們的應用程序組件之間流動的數據。 它可以是在一個組件內部流動的數據(本地狀態),也可以是在多個組件之間流動的數據(共享狀態)。 我們需要管理狀態,因為有時組件需要通過可靠的信息源相互通信。 在Redux中,這種可靠的信息源稱為存儲。
第1部分:React鉤子-什么和為什么 (Part 1: React hooks - the what and why)
什么是鉤子? (What are hooks?)
Hooks are functions that lets you access state without using a class component. Hooks are a more natural way of thinking about React. Instead of thinking of what lifecycle methods to use, you can now write components thinking about how and when your data needs to be used.
掛鉤是使您無需使用類組件即可訪問狀態的函數。 鉤子是思考React的一種更自然的方式。 現在,您無需考慮使用哪種生命周期方法,而可以編寫考慮如何以及何時使用數據的組件。
React hooks were introduced in October 2018 and released in February 2019. It is now available with React 16.8 and higher. React hooks became highly popular as soon as they were introduced.
React鉤子于2018年10月引入,并于2019年2月發布。它現在可用于React 16.8及更高版本。 引入后,React鉤子就變得非常流行。
為什么React鉤子如此受歡迎? (Why are React hooks so popular?)
- No boilerplate: To use hooks, you don't need to import any new libraries or write any boilerplate code. You can simply start using hooks out of the box in React 16.8 and up. 沒有樣板:使用鉤子,不需要導入任何新庫或編寫任何樣板代碼。 您可以在React 16.8及更高版本中直接使用開箱即用的鉤子。
- No need to use class components to use state: Traditionally, if you were using a functional component and decided that this component needs React state, you would have to convert it into a React class component. With the addition of hooks, you can use React state inside a functional component. 無需使用類組件來使用狀態:傳統上,如果您使用功能組件并確定該組件需要React狀態,則必須將其轉換為React類組件。 通過添加鉤子,可以在功能組件內部使用React狀態。
More logical way of thinking of React: You no longer have to think about when React mounts a component and what you should do in
componentDidMount
and remember to clean it up incomponentWillUnmount
. Now you can think more directly about how data is consumed by your component. React takes care of handling the mounting and cleanup functions for you.您再也不用去想陣營坐騎當一個組件,哪些是你應該做的:發生React的思維更合乎邏輯的方式
componentDidMount
記得把它清理干凈的componentWillUnmount
。 現在,您可以更直接地考慮組件如何使用數據。 React會為您處理安裝和清理功能。
有哪些常見的鉤子? (What are some common hooks?)
1. useState (1. useState)
useState is used to set and update state like this.state
in a class component.
useState用于在類組件中設置和更新類似this.state
狀態。
const [ state, setState] = useState(initialState);
2. useEffect (2. useEffect)
useEffect is used to carry out a function that does side effects. Side effects could include things like DOM manipulation, subscriptions, and API calls.
useEffect用于執行產生副作用的功能。 副作用可能包括諸如DOM操作,訂閱和API調用之類的事情。
useEffect(() => {document.title = 'New Title'
});
3. useReducer (3. useReducer)
useReducer works similar to how a reducer works in Redux. useReducer is used when state is more complex. You can actually use useReducer for everything you do with useState. It gives a dispatch function in addition to a state variable.
useReducer的工作方式與Redux中reducer的工作方式類似。 當狀態更復雜時使用useReducer。 實際上,您可以將useReducer用于useState的所有操作。 除了狀態變量外,它還提供了調度功能。
const [ state, dispatch ] = useReducer(reducer, initialArg, init);
4. useContext (4. useContext)
useContext is similar to the context API. In the context API, there is a Provider method and Consumer method. Similarly, with useContext, the closest Provider method is used to read data.
useContext與上下文API相似。 在上下文API中,有一個Provider方法和Consumer方法。 類似地,對于useContext,最接近的Provider方法用于讀取數據。
const value = useContext(MyContext);
For more detailed explanation of how each of these work, read the official docs.
有關這些功能的更多詳細說明,請閱讀官方文檔 。
第2部分:如何使用掛鉤進行狀態管理 (Part 2: How to use hooks for state management)
With React 16.8, you can use hooks out of the box.
使用React 16.8,您可以直接使用鉤子。
We are going to build an application to make a list of songs. Here is what it will do -
我們將構建一個應用程序來制作歌曲列表。 這是它的作用-
- Fetch a GraphQL API for a list of a songs and render it on the UI. 提取GraphQL API以獲得歌曲列表,并將其呈現在UI上。
- Have the ability to add a song to the list. 可以將歌曲添加到列表中。
- When the song gets added to the list, update the list on the frontend and store data on the backend. 當歌曲被添加到列表中時,在前端更新列表并將數據存儲在后端。
By the way, all the code is available on my GitHub. To see this in action, you can go to this CodeSandbox.
順便說一下,所有代碼都可以在我的GitHub上找到 。 要查看實際效果,可以轉到此CodeSandbox 。
We are going to use the GraphQL API with this app, but you can do the following steps with a REST API as well.
我們將在此應用程序中使用GraphQL API,但您也可以使用REST API執行以下步驟。
步驟0:主要要點 (Step 0: Main gist)
The main idea here is that we are going to use context
to pass data down to our components. We will be using hooks, useContext
and useReducer
, to read and update this state. We will be using useState
to store any local state. For doing side effects such as calling an API, we are going to use useEffect
.
這里的主要思想是我們將使用context
將數據向下傳遞到我們的組件。 我們將使用鉤子useContext
和useReducer
來讀取和更新此狀態。 我們將使用useState
來存儲任何本地狀態。 為了產生諸如調用API的副作用,我們將使用useEffect
。
Let's get started!
讓我們開始吧!
步驟1:設定內容 ( Step 1: Set up context)
import { createContext } from 'react';const Context = createContext({songs: []
});export default Context
步驟2:初始化您的狀態。 稱這個initialState (Step 2: Initialize your state. Call this initialState)
We are going to use this context from to initialize our state:
我們將使用from的上下文來初始化我們的狀態:
const initialState = useContext(Context);
步驟3:使用useReducer設置reducers (Step 3: Setup reducers using useReducer)
Now we are going to set up reducers with an initialState with useReducer
in App.js:
現在,我們將在App.js中使用useReducer
設置帶有initialState的reduceors:
const [ state, dispatch ] = useReducer(reducer, initialState);
步驟4:找出哪個是頂層組件。 (Step 4: Figure out which is the top level component.)
We will need to set up a Context Provider here. For our example, it will be App.js
. Also, pass in the dispatch returned from useReducer here so that children can have access to dispatch:
我們將需要在此處設置一個上下文提供程序。 對于我們的示例,它將是App.js
另外,在此處傳遞useReducer返回的調度,以便子代可以訪問調度:
<Context.Provider value={state,dispatch}>// children components<App /><Context.Provider value={state,dispatch}>
步驟5:現在使用useEffect掛鉤連接API (Step 5: Now hook up the APIs using the useEffect hook)
const {state, dispatch} = useContext(Context);useEffect(() => {if(songs) {dispatch({type: "ADD_CONTENT", payload: songs});}}, [songs]);
步驟6:更新狀態 (Step 6: Update state)
You can use useContext
and useReducer
to receive and update global application state. For local state like form components, you can use useState
.
您可以使用useContext
和useReducer
來接收和更新全局應用程序狀態。 對于表單組件之類的本地狀態,可以使用useState
。
const [artist, setArtist] = useState("");const [lyrics, setLyrics] = useState("");
And that's it! State management is now set up.
就是這樣! 現在建立了狀態管理。
Did you learn anything new? Have something to share? Tweet me on Twitter.
你學到新東西了嗎? 有東西要分享? 在Twitter上發給我。
翻譯自: https://www.freecodecamp.org/news/hooks-and-graphql/
react 生命掛鉤