React常用Hooks详解与代码示例
标题:React常用Hooks详解与代码示例
1. Hooks概述
- 定义:Hooks是React 16.8引入的特性,允许在函数组件中使用状态和其他React特性。
优点:
- 简化组件逻辑,避免类组件的复杂性。
- 提高代码复用性,支持自定义Hooks。
2. 常用Hooks详解与代码示例
1. useState
- 作用:在函数组件中添加状态。
语法:
const [state, setState] = useState(initialState);
示例:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>{count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
2. useEffect
- 作用:在函数组件中执行副作用操作(如数据获取、DOM操作等)。
语法:
useEffect(() => { // 副作用逻辑 return () => { // 清理逻辑 }; }, [dependencies]);
示例:
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000); return () => clearInterval(interval); // 清理定时器 }, []); return <div>Seconds: {seconds}</div>; }
3. useContext
- 作用:在函数组件中访问React的Context。
语法:
const value = useContext(MyContext);
示例:
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); function ThemedButton() { const theme = useContext(ThemeContext); return <button style={{ background: theme === 'dark' ? '#333' : '#FFF' }}>Themed Button</button>; }
4. useReducer
- 作用:用于复杂状态逻辑,类似于Redux的reducer。
语法:
const [state, dispatch] = useReducer(reducer, initialState);
示例:
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> <p>{state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); }
5. useRef
- 作用:用于访问DOM元素或存储可变值。
语法:
const refContainer = useRef(initialValue);
示例:
import React, { useRef } from 'react'; function TextInput() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); }
6. useMemo
- 作用:用于缓存计算结果,避免重复计算。
语法:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
示例:
import React, { useMemo, useState } from 'react'; function ExpensiveComponent({ a, b }) { const result = useMemo(() => { return a + b; // 假设这是一个昂贵的计算 }, [a, b]); return <div>Result: {result}</div>; }
7. useCallback
- 作用:用于缓存回调函数,避免不必要的重新创建。
语法:
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
示例:
import React, { useCallback, useState } from 'react'; function ParentComponent() { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount((prev) => prev + 1); }, []); return <ChildComponent onIncrement={increment} />; } function ChildComponent({ onIncrement }) { return <button onClick={onIncrement}>Increment</button>; }
3. 自定义Hooks
- 定义:将组件逻辑提取到可重用的函数中。
示例:
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 }; } function MyComponent() { const { data, loading } = useFetch('https://api.example.com/data'); if (loading) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }
4. 总结
常用Hooks:
useState
:管理状态。useEffect
:处理副作用。useContext
:访问Context。useReducer
:复杂状态逻辑。useRef
:访问DOM或存储可变值。useMemo
:缓存计算结果。useCallback
:缓存回调函数。
- 自定义Hooks:将逻辑提取为可重用函数,提升代码复用性。
通过掌握这些Hooks,可以更高效地开发React函数组件,提升代码质量和可维护性。