wordpress 微博模板成都網(wǎng)站搭建優(yōu)化推廣
文章目錄
- React Hooks 使用指南
- 常用 Hooks
- 使用規(guī)則
- 小結
React Hooks 使用指南
React Hooks 是 React 16.8 引入的一種新特性,允許在函數(shù)組件中使用狀態(tài)和其他 React 特性,而無需編寫類組件。以下是一些基礎的 Hooks 及其使用規(guī)則。
常用 Hooks
-
useState
用于在函數(shù)組件中添加狀態(tài)。import React, { useState } from 'react';function Counter() {const [count, setCount] = useState(0);return (<div><p>Count: {count}</p><button onClick={() => setCount(count + 1)}>Increment</button></div>); }
-
useEffect
處理副作用(如數(shù)據(jù)獲取、訂閱等)。import React, { useState, useEffect } from 'react';function DataFetchingComponent() {const [data, setData] = useState([]);useEffect(() => {fetch('https://api.example.com/data').then(response => response.json()).then(data => setData(data));}, []);return (<div>{data.map(item => (<div key={item.id}>{item.name}</div>))}</div>); }
-
useContext
共享數(shù)據(jù)的上下文。import React, { createContext, useContext } from 'react';const MyContext = createContext();function MyComponent() {const value = useContext(MyContext);return <div>{value}</div>; }function App() {return (<MyContext.Provider value="Hello, World!"><MyComponent /></MyContext.Provider>); }
-
useReducer
管理復雜狀態(tài)。import React, { useReducer } from 'react';const initialState = { count: 0 };function reducer(state, action) {switch (action.type) {case 'increment':return { count: state.count + 1 };case 'decrement':return { count: state.count - 1 };default:throw new Error();} }function Counter() {const [state, dispatch] = useReducer(reducer, initialState);return (<div>Count: {state.count}<button onClick={() => dispatch({ type: 'increment' })}>+</button><button onClick={() => dispatch({ type: 'decrement' })}>-</button></div>); }
-
自定義 Hook
創(chuàng)建可復用的邏輯。import { useState, useEffect } from 'react';function useFetch(url) {const [data, setData] = useState(null);const [loading, setLoading] = useState(true);useEffect(() => {fetch(url).then(response => response.json()).then(data => {setData(data);setLoading(false);});}, [url]);return { data, loading }; }
使用規(guī)則
-
只能在函數(shù)組件或自定義 Hook 中調(diào)用:避免在常規(guī) JavaScript 函數(shù)中使用。
-
必須在頂層調(diào)用:避免在循環(huán)、條件語句或嵌套函數(shù)中調(diào)用,確保每次渲染都以相同的順序調(diào)用 Hooks。
-
依賴數(shù)組:在
useEffect
和其他 Hooks 中,依賴數(shù)組用于控制副作用的執(zhí)行時機,確保正確管理狀態(tài)和性能。
小結
理解和掌握這些 Hooks 及其使用規(guī)則是使用 React 的重要基礎,可以使函數(shù)組件變得更加強大和靈活。
您好,我是肥晨。
歡迎關注我獲取前端學習資源,日常分享技術變革,生存法則;行業(yè)內(nèi)幕,洞察先機。