
🤍 前端开发工程师、技术日更博主、已过CET6
🍨 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1
🕠 牛客 高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》、《前端求职突破计划》
🍚 蓝桥云课 签约作者、上架课程《Vue.js 和 Egg.js 开发企业级健康管理项目》、《带你从入门到实战全面掌握 uni-app》
文章目录
-
- [Hooks 的主要类型](#Hooks 的主要类型)
-
- [1. `useState`](#1.
useState
) - [2. `useEffect`](#2.
useEffect
) - [3. `useContext`](#3.
useContext
) - [4. `useReducer`](#4.
useReducer
)
- [1. `useState`](#1.
- [Hooks 的使用规则](#Hooks 的使用规则)
- 结论
React Hooks 是 React 16.8 版本新增的功能,它允许你在不编写 class 组件的情况下使用 state 以及其他的 React 特性。Hooks 的出现极大地简化了函数组件的功能,使得它们能够承担更多之前只有 class 组件才能完成的任务。
Hooks 的主要类型
1. useState
useState
是一个允许你在函数组件中添加状态的 Hook。它返回一个状态变量和一个更新该状态的函数。
js
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
2. useEffect
useEffect
Hook 可以让你在函数组件中执行副作用操作,比如数据获取、订阅或者手动修改 DOM。
js
import React, { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
// 假设 fetchData 是一个异步函数,用于获取数据
fetchData().then(data => setData(data));
}, []); // 空数组表示只在组件挂载时执行
return (
<div>
{data ? <p>{data}</p> : <p>Loading...</p>}
</div>
);
}
3. useContext
useContext
Hook 提供了一种在函数组件中访问 React context 的方式,避免了组件树的层层传递。
js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme.background, color: theme.foreground }}>I am styled by theme context!</button>;
}
4. useReducer
useReducer
是 useState
的替代方案,适用于复杂的状态逻辑,尤其是当状态依赖于之前的状态或多个子值时。
js
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>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
Hooks 的使用规则
- 只能在函数组件的最顶层调用 Hooks。
- 只能在 React 函数组件中调用 Hooks,不要在其他地方调用(如在普通的 JavaScript 函数中)。
- 不要在循环、条件或嵌套函数中调用 Hooks。
结论
React Hooks 提供了一种强大的方式来在函数组件中添加状态和其他 React 特性,使得函数组件能够承担更多复杂的任务。通过使用 useState
、useEffect
、useContext
和 useReducer
等 Hooks,我们可以编写出更加简洁、可维护的代码。