【React 资料备份】React Hook
Hooks是React16.8一个新增项,是我们可以不用创建class组件就能使用状态和其他React特性
准备工作
-
升级react、react-dom
npm i react react-dom -S
状态钩子 State Hook
-
创建HooksTest.js
import React, { useState } from "react"; export default function HooksTest() { // useState(initialState),接收初始状态,返回一个状态变量和其更新函数 const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
更新函数类似setState,但它不会整合新旧状态
-
声明多个状态变量
export default function HooksTest() { const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]); return ( <div> <p>年龄 {age}</p> <p>水果 {fruit}</p> <ul> {todos.map(todo=><li key={todo.text}>{todo.text}</li>)} </ul> </div> ); }
副作用钩子 Effect Hook
-
更新HooksTest.js
import React, { useState, useEffect } from "react"; useEffect(() => { // Update the document title using the browser API document.title = `您点击了 ${count} 次`; });