React Hooks 是 React 16.8 版本引入的一项功能,它们使函数组件能够拥有类似于类组件的状态(state)和生命周期方法的能力,从而更容易实现和管理状态逻辑。通过使用 Hooks,你可以在无需编写类组件的情况下,实现更简洁、可读性更高的代码。
以下是 React Hooks 的一些常用的内置 Hook:
-
useState:
- 用于在函数组件中添加状态。
- 语法:
const [state, setState] = useState(initialState);
- 示例:
import React, { useState } from 'react'; function Example() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
-
useEffect:
- 用于在函数组件中执行副作用操作,比如数据获取、订阅、手动修改 DOM。
- 语法:
useEffect(() => { /* effect */ }, [dependencies]);
- 示例:
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
-
useContext:
- 用于在函数组件中访问 React 上下文。
- 语法:
const contextValue = useContext(MyContext);
- 示例:
import React, { useContext } from 'react'; const MyContext = React.createContext(); function Example() { const contextValue = useContext(MyContext); return <p>{contextValue}</p>; }
-
useReducer:
- 用于在函数组件中管理复杂的状态逻辑。
- 语法:
const [state, dispatch] = useReducer(reducer, initialState);
- 示例:
import React, { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </div> ); }
-
useCallback 和 useMemo:
- 用于性能优化,避免在每次渲染时重新创建回调函数或计算结果。
useCallback
: 缓存回调函数,防止不必要的重新渲染。useMemo
: 缓存计算结果,避免不必要的重复计算。- 示例:
import React, { useState, useCallback, useMemo } from 'react'; function Example() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { setCount(count + 1); }, [count]); const doubledCount = useMemo(() => { return count * 2; }, [count]); return ( <div> <p>You clicked {count} times</p> <p>Doubled count: {doubledCount}</p> <button onClick={handleClick}> Click me </button> </div> ); }
这些是 React Hooks 的一些基础用法。使用这些 Hooks 可以使你更方便地处理组件的状态和副作用,从而提高代码的可维护性和可读性。