You clicked {count} times
setCount(count + 1)}>
Click me
);
}
“`
在这里,useState 是一个 Hook,我们在函数组件中调用它以给它添加一些本地状态。React 将在重新渲染之间保留这个状态。useState 返回一对值:currentstate 值和允许你更新它的函数。
可以从事件处理程序或其他位置调用该函数,这与类中的 this.setState 类似,除了其不会把旧的和新的状态合并在一起。
声明多个状态变量
可以在单个组件中多次使用 State Hook:
function ExampleWithManyStates() { // Declare multiple state variables! const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]); // ... }
数组解构语法允许我们给状态变量取不同的名字,这些变量是我们通过调用 useState 声明的,这不是 useState API 的一部分。相反,React 假设如果多次调用 useState,那么在每次渲染的时候要遵循相同的顺序来做。
Effect Hook
你之前很可能已经执行了数据提取、订阅、或手工改变来自 React 组件的 DOM。我们称这些操作为“副作用(side effect)”,因为它们会影响其他组件,并且在渲染过程中无法完成。
Effect Hook、useEffect,增加了从函数组件执行副作用的功能。它与 React 类中的 componentDidMount、componentDidUpdate、和 componentWillUnmount 有相同的功能,但是统一为单个 API。(我们将展示一个例子,该示例在 Using the Effect Hook 中对 useEffect 和这些方法进行比较。)
例如,此组件在 React 更新 DOM 后设置文档标题:
“`
import { useState, useEffect } from ‘react’;
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = You clicked ${count} times
;
});
return (
You clicked {count} times
<button onClick={() => setCount(count + 1)}>
Click me