什么是 Hooks?
React Hooks 是在函数组件中使用状态和生命周期特性的方法。
基础 Hooks
useState
tsx
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>计数:{count}</p>
<button onClick={() => setCount(count + 1)}>
增加
</button>
</div>
)
}useEffect
tsx
import { useEffect, useState } from 'react'
function DataFetcher() {
const [data, setData] = useState(null)
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(setData)
}, [])
return <div>{data ? JSON.stringify(data) : '加载中...'}</div>
}高级 Hooks
自定义 Hooks
tsx
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
return initialValue
}
})
const setValue = (value) => {
try {
setStoredValue(value)
window.localStorage.setItem(key, JSON.stringify(value))
} catch (error) {
console.error('Failed to save to localStorage', error)
}
}
return [storedValue, setValue]
}使用场景
传统类组件 vs 函数组件 + Hooks
类组件:
tsx
class Counter extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
componentDidMount() {
// 生命周期逻辑
}
componentDidUpdate() {
// 更新逻辑
}
render() {
return <div>{this.state.count}</div>
}
}函数组件 + Hooks:
tsx
function Counter() {
const [count, setCount] = useState(0)
useEffect(() => {
// 生命周期逻辑
}, [])
return <div>{count}</div>
}性能优化
使用 useMemo
tsx
const expensiveValue = useMemo(() => {
return computeExpensiveValue(a, b)
}, [a, b])使用 useCallback
tsx
const handleClick = useCallback(() => {
doSomething(a, b)
}, [a, b])总结
React Hooks 让函数组件更加强大,代码更简洁,逻辑复用更加容易。
评论
0评论加载中…