问答题1291/1620列举几个常见的 Hook?

难度:
2021-07-04 创建

参考答案:

在 React 中,Hooks 是一组可以让函数组件拥有状态和副作用的 API。

以下是一些常见的 Hook 及其用途:

1. useState

  • 用途:在函数组件中添加状态。
  • 示例
    1import React, { useState } from 'react'; 2 3function Counter() { 4 const [count, setCount] = useState(0); 5 6 return ( 7 <div> 8 <p>You clicked {count} times</p> 9 <button onClick={() => setCount(count + 1)}>Click me</button> 10 </div> 11 ); 12}

2. useEffect

  • 用途:在函数组件中处理副作用,如数据获取、订阅和手动 DOM 操作。
  • 示例
    1import React, { useEffect, useState } from 'react'; 2 3function Example() { 4 const [data, setData] = useState(null); 5 6 useEffect(() => { 7 fetch('https://api.example.com/data') 8 .then(response => response.json()) 9 .then(data => setData(data)); 10 }, []); // 空数组表示只在组件挂载时执行一次 11 12 return <div>{data ? `Data: ${data}` : 'Loading...'}</div>; 13}

3. useContext

  • 用途:在组件中访问 React 的 Context。
  • 示例
    1import React, { useContext, createContext } from 'react'; 2 3const MyContext = createContext('defaultValue'); 4 5function Display() { 6 const value = useContext(MyContext); 7 return <div>{value}</div>; 8} 9 10function App() { 11 return ( 12 <MyContext.Provider value="Hello, World!"> 13 <Display /> 14 </MyContext.Provider> 15 ); 16}

4. useReducer

  • 用途:管理复杂状态逻辑,类似于 Redux 的 reducer。
  • 示例
    1import React, { useReducer } from 'react'; 2 3const initialState = { count: 0 }; 4 5function reducer(state, action) { 6 switch (action.type) { 7 case 'increment': 8 return { count: state.count + 1 }; 9 case 'decrement': 10 return { count: state.count - 1 }; 11 default: 12 throw new Error(); 13 } 14} 15 16function Counter() { 17 const [state, dispatch] = useReducer(reducer, initialState); 18 19 return ( 20 <div> 21 <p>Count: {state.count}</p> 22 <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> 23 <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> 24 </div> 25 ); 26}

5. useMemo

  • 用途:优化性能,通过记忆化计算结果,避免不必要的重新计算。
  • 示例
    1import React, { useMemo, useState } from 'react'; 2 3function ExpensiveComponent({ compute }) { 4 const result = useMemo(() => compute(), [compute]); 5 return <div>Result: {result}</div>; 6} 7 8function App() { 9 const [count, setCount] = useState(0); 10 11 const compute = () => { 12 // 模拟一个计算过程 13 return count * 2; 14 }; 15 16 return ( 17 <div> 18 <button onClick={() => setCount(count + 1)}>Increment</button> 19 <ExpensiveComponent compute={compute} /> 20 </div> 21 ); 22}

6. useCallback

  • 用途:记忆化回调函数,避免在依赖项变化时重新创建函数。
  • 示例
    1import React, { useCallback, useState } from 'react'; 2 3function Button({ onClick }) { 4 console.log('Button rendered'); 5 return <button onClick={onClick}>Click me</button>; 6} 7 8function App() { 9 const [count, setCount] = useState(0); 10 11 const handleClick = useCallback(() => { 12 alert('Button clicked!'); 13 }, []); // 依赖项为空数组表示回调函数不会变化 14 15 return ( 16 <div> 17 <p>Count: {count}</p> 18 <button onClick={() => setCount(count + 1)}>Increment</button> 19 <Button onClick={handleClick} /> 20 </div> 21 ); 22}

7. useRef

  • 用途:在函数组件中创建可变的引用,通常用于访问 DOM 元素或保存任何可变数据。
  • 示例
    1import React, { useRef } from 'react'; 2 3function FocusInput() { 4 const inputRef = useRef(null); 5 6 const handleClick = () => { 7 inputRef.current.focus(); 8 }; 9 10 return ( 11 <div> 12 <input ref={inputRef} type="text" /> 13 <button onClick={handleClick}>Focus the input</button> 14 </div> 15 ); 16}

这些 Hooks 提供了处理状态、副作用、上下文、性能优化等常见需求的功能,使得函数组件变得更加灵活和强大。

最近更新时间:2024-08-10

赞赏支持

题库维护不易,您的支持就是我们最大的动力!