React中的Hooks
AWS 安全直播!
1 定义:
要解释 React 中的hooks概念,首先需要解释以下术语:
✔️ React 组件是一个渲染 HTML 元素的函数。React 组件可以是类,也可以是函数。
✔️ React 类 (组件)使用 React 生命周期来管理状态和组件事件。
✔️ React 生命周期是指 React 组件生命周期内发生的一系列事件。生命周期事件允许开发者在 React 组件生命周期的不同阶段与其进行交互。
✔️ React 函数(函数组件)使用hooks来管理状态和组件事件。
2. 什么是钩子?
- Hooks是一种函数,它允许开发人员管理状态并访问 React 生命周期功能,而无需编写类。
为了解释钩子,我们可以使用以下类比:
React 类就像洗衣机。它们有生命周期,可以完成洗涤衣物等任务。
React 函数就像没有生命周期的洗衣机,必须配合特定的洗涤工具才能正常使用。
Hooks就是这些特定的工具⚙️ 它们允许 React 函数访问 React 生命周期特性。
🔸 UseState() 钩子:
- useState() Hook:允许你管理 React 组件的状态。
function App() {
const [number, setNumber] = useState(0);
return (
<div>
<h1>Number: [number)</h1>
<button onClick={() => setNumber(number+ 1)}>+1</button>
</div>
);
}
这个 React 组件使用useState() hook 来管理数字的状态。number 变量表示数字的当前状态。setNumber ()函数允许你修改数字的状态。
➡️useState () hook 返回 2 个值:状态的当前值和一个允许修改状态的函数。
📌市面上有许多不同类型的挂钩,每一种都有其自身的用途。
以下是一些最常见的鱼钩:
• useState():用于管理 React 组件的状态。
• useEffect():用于对 React 组件环境的变化做出反应。
• useContext():用于从 React 组件访问上下文。
• useReducer():用于管理 React 组件的复杂状态。
• useParams()等
🔸 UseEffect() 钩子:
useEffect() Hook允许 React 组件在特定时间以及某些属性或状态发生变化时执行操作。它对于执行副作用非常有用,例如:
- 数据获取
- 更新 DOM
- 添加或移除事件监听器
The useEffect() hook takes 2 arguments: from a function and an array of dependencies :
useEffect(() => {
// Code to execute after rendering the component
// and after each update
}, [dependency]);
- ✔️该函数在组件渲染后以及每次更新后执行。
- ✔️依赖关系表允许您指定触发函数执行的值。如果依赖关系数组中的某个值发生变化,则会执行该函数。
使用useEffect()钩子更新 DOM的示例:
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}
在这个例子中,useEffect()钩子用于在count变量的值每次发生变化时更新页面标题。这是因为count变量包含在依赖关系表中。
使用useEffect()钩子获取数据的示例:
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://api.github.com/users')
.then((response) => response.json())
.then((data) => setUsers(data));
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.login}</li>
))}
</ul>
);
}
在这个例子中,useEffect()钩子用于从GitHub API获取数据。该函数只在组件初始渲染之后执行一次。这是因为依赖关系表为空[ ] 。
- ✔️Hooks 是管理 React 组件状态和副作用的强大方法。
- ✔️useEffect () hook 对于执行异步操作(例如数据获取)特别有用。
示例:添加或移除事件监听器
可以使用 useEffect() hook 在 React 组件中添加或移除事件监听器。
要添加事件监听器,只需在useEffect()钩子函数中使用addEventListener()函数即可。
The addEventListener() function takes two arguments: the event to listen for and the function to callback that will be called when the event occurs.
window.removeEventListener(‘click’, handlclick]);
以下是一个添加按钮点击事件监听器的示例:
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
const button = document.getElementById('button');
const handleClick = () => {
setCount((prevCount) => prevCount + 1);
};
button.addEventListener('click', handleClick);
return () => {
// Cleanup the event listener when the component is unmounted
button.removeEventListener('click', handleClick);
};
}, []);
return (
<div>
<h1>Count: {count}</h1>
<button id="button">+1</button>
</div>
);
}