React钩子函数也称为React Hooks,是React16.8版本新增的功能,用于在函数组件中添加状态和生命周期等特性。React钩子函数有以下几种:
- useState:用于在函数组件中添加状态,并返回一个数组,第一个值为状态值,第二个值为更新状态的函数。
使用示例:
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:用于在函数组件中添加生命周期的功能,包括componentDidMount、componentDidUpdate和componentWillUnmount等。
使用示例:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
- useContext:用于在函数组件中访问React Context的值。
使用示例:
import React, { useContext } from 'react';
import { ThemeContext } from './theme-context';
function ThemeButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}
- useReducer:用于在函数组件中管理状态的复杂逻辑。
使用示例:
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:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}
- useCallback:用于在函数组件中缓存函数,避免因函数重新创建导致组件的重新渲染。
使用示例:
import React, { useState, useCallback } from 'react';
function Foo({ onClick }) {
return <button onClick={onClick}>Click me</button>;
}
function Example() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<Foo onClick={handleClick} />
</div>
);
}
- useMemo:用于在函数组件中缓存计算结果,避免因计算结果重新创建导致组件的重新渲染。
使用示例:
import React, { useState, useMemo } from 'react';
function Example() {
const [count, setCount] = useState(0);
const expensiveCalculation = useMemo(() => {
console.log('Calculating...');
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += i;
}
return result;
}, []);
return (
<div>
<p>You clicked {count} times</p>
<p>The expensive calculation result is {expensiveCalculation}</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
以上是React Hooks的六种常用函数,它们可以帮助我们在函数组件中实现更复杂的逻辑。