千锋教育2022版React全家桶教程_react零基础入门到项目实战完整版

1.为什么用Hook?
① Hooks 提供了 useState
Hook,使函数组件能够拥有自己的内部状态。您可以使用 useState
来声明和更新状态变量,而不需要使用类组件中的 this.state
和 this.setState
。
②通过 useEffect
Hook,您可以在函数组件中处理副作用,比如订阅数据、请求数据、操作 DOM 等。
③自定义 Hooks:Hooks 还支持创建自定义的可重用 Hooks,用于在多个组件之间共享逻辑。自定义 Hooks 将具体的逻辑抽象出来,使其在不同的组件中都能重复使用,提高了代码的可维护性和重用性
2.使用State Hook
2.1 声明State变量
在 class 中,我们通过在构造函数中设置 this.state
为 { count: 0 }
来初始化 count
state 为 0
:
class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; }
在函数组件中,我们没有 this
,所以我们不能分配或读取 this.state
。我们直接在组件中调用 useState
Hook:
import React, { useState } from 'react'; function Example() { // 声明一个叫 “count” 的 state 变量 const [count, setCount] = useState(0); console.log(count, setCount) }
2.2使用多个state变量
将 state 变量声明为一对 [something, setSomething]
也很方便,因为如果我们想使用多个 state 变量,它允许我们给不同的 state 变量取不同的名称:
function ExampleWithManyStates() { // 声明多个 state 变量 const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: '学习 Hook' }]);
在以上组件中,我们有局部变量 age
,fruit
和 todos
,并且我们可以单独更新它们:
function handleOrangeClick() { // 和 this.setState({ fruit: 'orange' }) 类似 setFruit('orange'); }