
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
前言
楼主最近在整理 React Hooks 的一些资料,为项目重构作准备,下午整理成了这篇文章。
如果之前没接触过相关概念,那么通过这篇文章, 你将会了什么是React Hooks , 它是做什么的 , 以及如何使用。
下面我会用一个具体的例子来说明, 通过这个例子, 你将了解:
- 如何使用
React Hooks - 如何用
React Class components实现同样的逻辑
快速开始
先快速搭建一个项目:
npx create-react-app exploring-hooks
Demo in setState
1import React, { Component } from "react"; 2 3export default class Button extends Component { 4 state = { buttonText: "Click me, please" }; 5 6 handleClick = () => { 7 this.setState(() => { 8 return { buttonText: "Thanks, been clicked!" }; 9 }); 10 }; 11 12 render() { 13 const { buttonText } = this.state; 14 return <button onClick={this.handleClick}>{buttonText}</button>; 15 } 16}
功能非常简单: 点一下按钮, 就更新 button 的 text。
Demo in Hooks
这里,我们将不再使用 setState 和 ES6 Class. 轮到我们的Hooks登场了:
import React, { useState } from "react";
引入 useState 就意味着我们将要把一些状态管理置于组件内部, 而且我们的 React Component 将不再是一个 ES6 class, 取而代之的是一个简单的纯函数。
引入 useState 之后,我们将从中取出一个含有两个元素的数组:
const [buttonText, setButtonText] = useState("Click me, please");
如果对这个语法有疑问, 可以参考 ES6 解构.
这两个值的名字, 你可以随意取, 和 React 无关,但是还是建议你根据使用的目的取一个足够具体和清晰的名字。
就比如上面写的, 一个代表是 buttonText 的 值, 另一个代表是 setButtonText 的 更新函数。
给 useState 传入的是一个初始值, 比如, 这个按钮的最初要显示的是: Click me, please。
这个简单的例子的代码全貌:
1import React, { useState } from "react"; 2 3export default function Button() { 4 const [buttonText, setButtonText] = useState("Click me, please"); 5 6 function handleButtonClick() { 7 return setButtonText("Thanks, been clicked!"); 8 } 9 10 return <button onClick={handleButtonClick}>{buttonText}</button>; 11}
下面我们将介绍如何使用 Hooks 获取数据。
使用 React Hooks 获取数据
在这之前, 我们都是在 componentDidMount 函数里调API:
1import React, { Component } from "react"; 2 3export default class DataLoader extends Component { 4 5state = { data: [] }; 6 7 async componentDidMount() { 8 try { 9 const response = await fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`); 10 if (!response.ok) { 11 throw Error(response.statusText); 12 } 13 const json = await response.json(); 14 this.setState({ data: json }); 15 } catch (error) { 16 console.log(error); 17 } 18 } 19 20 render() { 21 return ( 22 <div> 23 <ul> 24 {this.state.data.map(el => ( 25 <li key={el.id}>{el.name}</li> 26 ))} 27 </ul> 28 </div> 29 ); 30 } 31}
这种代码大家想必都非常熟悉了, 下面我们用 Hooks 来重写:
1import React, { useState, useEffect } from "react"; 2 3export default function DataLoader() { 4 const [data, setData] = useState([]); 5 6 useEffect(() => { 7 fetch("http://localhost:3001/links/") 8 .then(response => response.json()) 9 .then(data => setData(data)); 10 }); 11 12 return ( 13 <div> 14 <ul> 15 {data.map(el => ( 16 <li key={el.id}>{el.title}</li> 17 ))} 18 </ul> 19 </div> 20 ); 21}
运行一下就会发现,哎呦, 报错了, 无限循环:

原因其实也非常简单, useEffect 存在的目的 和componentDidMount, componentDidUpdate, and componentWillUnmount是一致的, 每次state 变化 或者 有新的props 进来的时候,componentDidUpdate componentDidUpdate` 都会执行。
要解决这个 "bug" 也非常简单, 给 useEffect 传入一个空数组作为第二个参数:
1useEffect(() => { 2 fetch("http://localhost:3001/links/") 3 .then(response => response.json()) 4 .then(data => setData(data)); 5 },[]); // << super important array
关于 Hook 的详细信息可以参考: Using the Effect Hook
看到这你可能会按捺不住内心的小火苗,要去重构项目,个人还不建议这么做,因为接下来的几个版本中可能会有变化, 就像Ryan Florence 建议的:
Hooks are not the endgame for React data loading.
Data loading is probably the most common effect in an app.
Don't be in a big hurry to migrate to hooks for data unless you're okay migrating again when suspense for data is stable.
Own your churn.
无论怎么说, useEffect 的出现还是一件好事。
能把 Hooks 用于 Render props 吗
能显然是能的, 不过没什么意义, 比如把上面的代码改一下:
1import React, { useState, useEffect } from "react"; 2 3export default function DataLoader(props) { 4 const [data, setData] = useState([]); 5 6 useEffect(() => { 7 fetch("http://localhost:3001/links/") 8 .then(response => response.json()) 9 .then(data => setData(data)); 10 }, []); 11 12 return props.render(data) 13}
从外部传入一个render即可, 但是这样做毫无意义: Reack Hooks 本身就是为了解决组件间逻辑公用的问题的。
定义你的 React Hook
还是上面的例子,我们把取数据的逻辑抽出来:
1// useFetch.tsx 2import { useState, useEffect } from "react"; 3 4export default function useFetch(url) { 5 const [data, setData] = useState([]); 6 7 useEffect(() => { 8 fetch(url) 9 .then(response => response.json()) 10 .then(data => setData(data)); 11 }, [] ); 12 13 return data; 14} 15
在其他组件中引用:
1import React from "react"; 2import useFetch from "./useFetch"; 3 4export default function DataLoader(props) { 5 const data = useFetch("http://localhost:3001/links/"); 6 return ( 7 <div> 8 <ul> 9 {data.map(el => ( 10 <li key={el.id}>{el.title}</li> 11 ))} 12 </ul> 13 </div> 14 ); 15}

React Hooks 的本质
上面我们说到 Reack Hooks 本身就是为了解决组件间逻辑公用的问题的。
回顾我们现在的做法,几乎都是面向生命周期编程:

Hooks 的出现是把这种面向生命周期编程变成了面向业务逻辑编程,让我们不用再去关注生命周期:

而且, 最新的React 中, 预置了大量的Hooks, 最重要两个的就是: useState and useEffect.
useState 使我们在不借助 ES6 class 的前提下, 在组件内部使用 state 成为可能。
useEffect 取代了 componentDidMount, componentDidUpdate, and componentWillUnmount, 提供了一个统一的API。
除了这两个之外, 可以在官方文档中了解更多:

一个显而易见的事实是, 过不来了多久, 我们就会有三种创建React components 的姿势:
- functional components
- class components
- functional components with hooks
作为一个 React 忠实粉丝, 看到这些积极的变化实在是令人感到愉悦。
Hooks 更多学习资源
还有很多帮助我们更好的学和掌握 React Hooks, 也在这里分享一下:
首先还是官方文档: Introducing Hooks, Hooks at a Glance 是稍微深入一些的内容。
然后是一个入门教程: Build a CRUD App in React with Hooks.
关于状态管理, 还有一个比较有趣的文章: useReducer, don't useState
比较有意思的是, 我们最后会大量使用 useReducer, 形势和 Redux 非常类似:
1function reducer(state, action) { 2 const { past, future, present } = state 3 switch (action.type) { 4 case 'UNDO': 5 const previous = past[past.length - 1] 6 const newPast = past.slice(0, past.length - 1) 7 return { 8 past: newPast, 9 present: previous, 10 future: [present, ...future], 11 } 12 case 'REDO': 13 const next = future[0] 14 const newFuture = future.slice(1) 15 return { 16 past: [...past, present], 17 present: next, 18 future: newFuture, 19 } 20 default: 21 return state 22 } 23} 24
这也从侧面证明了Redux 在社区中的影响力( 其实这两个东西的核心开发者是同一个人 )。
总结
- Hooks 的出现简化了逻辑,把面向生命周期编程变成了面向业务逻辑编程,为逻辑复用提供了更多可能。
- Hooks 是未来的方向。
大概就是这些, 希望能对大家有些启发和帮助。
才疏学浅,行文若有纰漏,还请各位大大帮忙指正, 谢谢。
本文同步分享在 博客“皮小蛋”(SegmentFault)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。