Open QC-L opened 5 years ago
State Hook 的示例。可以在函数组件中使用 state。
import React, { useState } from 'react'; function Example() { // 声明一个叫 "count" 的 state 变量。 const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
useState
声明多个 state,其中 useState 语法用到了数组解构,这样可以为 state 起名字。
function ExampleWithManyStates() { // 声明多个 state 变量! const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]); // ... }
Effect Hook 的示例。可以在函数组件中增加操作副作用相关的能力。
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // 相当于 componentDidMount 和 componentDidUpdate: useEffect(() => { // 使用浏览器的 API 更新页面标题 document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
useEffect
使用 useEffect 时返回一个函数,可以清除副作用。
useEffect(() => { ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; });
创建自己的 Hook 官方给出的自定义 Hook 的例子,这是一段抽离状态逻辑的代码,可以实现在多个函数组件中复用。 这点在 class 组件中无法做到
import React, { useState, useEffect } from 'react'; function useFriendStatus(friendID) { const [isOnline, setIsOnline] = useState(null); function handleStatusChange(status) { setIsOnline(status.isOnline); } useEffect(() => { ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); }; }); return isOnline; }
useSomething
useContent
useReducer
赞啊,Hooks 和 Lifecycle 对应有一个回答解释的还错,实际使用的时候可以参考 https://stackoverflow.com/questions/53214465/how-to-use-lifecycle-methods-with-hooks-in-react/53253750#53253750
React Hook 学习笔记
阅读 React Hook 简介
阅读 React Hook 概览
State Hook 的示例。可以在函数组件中使用 state。
useState
就是 Hook。参数为 state 的初始值。声明多个 state,其中 useState 语法用到了数组解构,这样可以为 state 起名字。
Effect Hook 的示例。可以在函数组件中增加操作副作用相关的能力。
useEffect
可以生成副作用函数。使用
useEffect
时返回一个函数,可以清除副作用。useEffect
与useState
相同,都可以多次调用。创建自己的 Hook 官方给出的自定义 Hook 的例子,这是一段抽离状态逻辑的代码,可以实现在多个函数组件中复用。 这点在 class 组件中无法做到
useSomething
的形式。useContent
,useReducer
等。