当前位置:   article > 正文

React Hooks 使用详解

使用 usestate api 时,传入一个函数

本文对 16.8 版本之后 React 发布的新特性 Hooks 进行了详细讲解,并对一些常用的 Hooks 进行代码演示,希望可以对需要的朋友提供点帮助。

一、Hooks 简介

HooksReact v16.7.0-alpha 中加入的新特性。它可以让你在 class 以外使用 state 和其他 React 特性。 本文就是演示各种 Hooks API 的使用方式,对于内部的原理这里就不做详细说明。


二、Hooks 初体验

Example.js

  1. import React, { useState } from 'react';
  2. function Example() {
  3. // 声明一个名为“count”的新状态变量
  4. const [count, setCount] = useState(0);
  5. return (
  6. <div>
  7. <p>You clicked {count} times</p>
  8. <button onClick={() => setCount(count + 1)}>
  9. Click me
  10. </button>
  11. </div>
  12. );
  13. }
  14. export default Example;
  15. 复制代码

useState 就是一个 Hook,可以在我们不使用 class 组件的情况下,拥有自身的 state,并且可以通过修改 state 来控制 UI 的展示。


三、常用的两个 Hooks

1、useState

语法

const [state, setState] = useState(initialState)

  • 传入唯一的参数: initialState,可以是数字,字符串等,也可以是对象或者数组。
  • 返回的是包含两个元素的数组:第一个元素,state 变量,setState 修改 state值的方法。
与在类中使用 setState 的异同点:
  • 相同点:也是异步的,例如在 onClick 事件中,调用两次 setState,数据只改变一次。
  • 不同点:类中的 setState 是合并,而函数组件中的 setState 是替换。
使用对比

之前想要使用组件内部的状态,必须使用 class 组件,例如:

Example.js

  1. import React, { Component } from 'react';
  2. export default class Example extends Component {
  3. constructor(props) {
  4. super(props);
  5. this.state = {
  6. count: 0
  7. };
  8. }
  9. render() {
  10. return (
  11. <div>
  12. <p>You clicked {this.state.count} times</p>
  13. <button onClick={() => this.setState({ count: this.state.count + 1 })}>
  14. Click me
  15. </button>
  16. </div>
  17. );
  18. }
  19. }
  20. 复制代码

而现在,我们使用函数式组件也可以实现一样的功能了。也就意味着函数式组件内部也可以使用 state 了。

Example.js

  1. import React, { useState } from 'react';
  2. function Example() {
  3. // 声明一个名为“count”的新状态变量
  4. const [count, setCount] = useState(0);
  5. return (
  6. <div>
  7. <p>You clicked {count} times</p>
  8. <button onClick={() => setCount(count + 1)}>
  9. Click me
  10. </button>
  11. </div>
  12. );
  13. }
  14. export default Example;
  15. 复制代码
优化

创建初始状态是比较昂贵的,所以我们可以在使用 useState API 时,传入一个函数,就可以避免重新创建忽略的初始状态。

普通的方式:

  1. // 直接传入一个值,在每次 render 时都会执行 createRows 函数获取返回值
  2. const [rows, setRows] = useState(createRows(props.count));
  3. 复制代码

优化后的方式(推荐):

  1. // createRows 只会被执行一次
  2. const [rows, setRows] = useState(() => createRows(props.count));
  3. 复制代码

2、useEffect

之前很多具有副作用的操作,例如网络请求,修改 UI 等,一般都是在 class 组件的 componentDidMount 或者 componentDidUpdate生命周期中进行操作。而在函数组件中是没有这些生命周期的概念的,只能 return 想要渲染的元素。 但是现在,在函数组件中也有执行副作用操作的地方了,就是使用 useEffect 函数。

语法

useEffect(() => { doSomething });

两个参数:

  • 第一个是一个函数,是在第一次渲染以及之后更新渲染之后会进行的副作用。

    • 这个函数可能会有返回值,倘若有返回值,返回值也必须是一个函数,会在组件被销毁时执行。
  • 第二个参数是可选的,是一个数组,数组中存放的是第一个函数中使用的某些副作用属性。用来优化 useEffect

    • 如果使用此优化,请确保该数组包含外部作用域中随时间变化且 effect 使用的任何值。 否则,您的代码将引用先前渲染中的旧值。
    • 如果要运行 effect 并仅将其清理一次(在装载和卸载时),则可以将空数组([])作为第二个参数传递。 这告诉React你的 effect 不依赖于来自 props 或 state 的任何值,所以它永远不需要重新运行。

虽然传递 [] 更接近熟悉的 componentDidMountcomponentWillUnmount 执行规则,但我们建议不要将它作为一种习惯,因为它经常会导致错误。

使用对比

假如此时我们有一个需求,让 document 的 title 与 Example 中的 count 次数保持一致。

使用 class 组件:

Example.js

  1. import React, { Component } from 'react';
  2. export default class Example extends Component {
  3. constructor(props) {
  4. super(props);
  5. this.state = {
  6. count: 0
  7. };
  8. }
  9. componentDidMount() {
  10. document.title = `You clicked ${ this.state.count } times`;
  11. }
  12. componentDidUpdate() {
  13. document.title = `You clicked ${ this.state.count } times`;
  14. }
  15. render() {
  16. return (
  17. <div>
  18. <p>You clicked {this.state.count} times</p>
  19. <button onClick={() => this.setState({ count: this.state.count + 1 })}>
  20. Click me
  21. </button>
  22. </div>
  23. );
  24. }
  25. }
  26. 复制代码

而现在在函数组件中也可以进行副作用操作了。

Example.js

  1. import React, { useState, useEffect } from 'react';
  2. function Example() {
  3. // 声明一个名为“count”的新状态变量
  4. const [count, setCount] = useState(0);
  5. // 类似于 componentDidMount 和 componentDidUpdate:
  6. useEffect(() => {
  7. // 使用浏览器API更新文档标题
  8. document.title = `You clicked ${count} times`;
  9. });
  10. return (
  11. <div>
  12. <p>You clicked {count} times</p>
  13. <button onClick={() => setCount(count + 1)}>
  14. Click me
  15. </button>
  16. </div>
  17. );
  18. }
  19. export default Example;
  20. 复制代码

不仅如此,我们可以使用 useEffect 执行多个副作用(可以使用一个 useEffect 执行多个副作用,也可以分开执行)

  1. useEffect(() => {
  2. // 使用浏览器API更新文档标题
  3. document.title = `You clicked ${count} times`;
  4. });
  5. const handleClick = () => {
  6. console.log('鼠标点击');
  7. }
  8. useEffect(() => {
  9. // 给 window 绑定点击事件
  10. window.addEventListener('click', handleClick);
  11. });
  12. 复制代码

现在看来功能差不多了。但是在使用类组件时,我们一般会在 componentWillMount 生命周期中进行移除注册的事件等操作。那么在函数组件中又该如何操作呢?

  1. useEffect(() => {
  2. // 使用浏览器API更新文档标题
  3. document.title = `You clicked ${count} times`;
  4. });
  5. const handleClick = () => {
  6. console.log('鼠标点击');
  7. }
  8. useEffect(() => {
  9. // 给 window 绑定点击事件
  10. window.addEventListener('click', handleClick);
  11. return () => {
  12. // 给 window 移除点击事件
  13. window.addEventListener('click', handleClick);
  14. }
  15. });
  16. 复制代码

可以看到,我们传入的第一个参数,可以 return 一个函数出去,在组件被销毁时,会自动执行这个函数

优化 useEffect

上面我们一直使用的都是 useEffect 中的第一个参数,传入了一个函数。那么 useEffect 的第二个参数呢?

useEffect 的第二个参数是一个数组,里面放入在 useEffect 使用到的 state 值,可以用作优化,只有当数组中 state 值发生变化时,才会执行这个 useEffect

  1. useEffect(() => {
  2. // 使用浏览器API更新文档标题
  3. document.title = `You clicked ${count} times`;
  4. }, [ count ]);
  5. 复制代码

Tip:如果想模拟 class 组件的行为,只在 componetDidMount 时执行副作用,在 componentDidUpdate 时不执行,那么 useEffect 的第二个参数传一个 [] 即可。(但是不建议这么做,可能会由于疏漏出现错误)


四、其他 Hoos API

1、useContext

语法

const value = useContext(MyContext);

接受上下文对象(从中React.createContext返回的值)并返回该上下文的当前上下文值。当前上下文值由树中调用组件上方value最近的prop 确定<MyContext.Provider>。

useContext(MyContext) 则相当于 static contextType = MyContext 在类中,或者 <MyContext.Consumer>

用法

App.js 文件中创建一个 context,并将 context 传递给 Example 子组件

App.js

  1. import React, { createContext } from 'react';
  2. import Example from './Example';
  3. import './App.css';
  4. export const ThemeContext = createContext(null);
  5. export default () => {
  6. return (
  7. <ThemeContext.Provider value="light">
  8. <Example />
  9. </ThemeContext.Provider>
  10. )
  11. }
  12. 复制代码

Example 组件中,使用 useContext API 可以获取到传入的 context

Example.js

  1. import React, { useContext } from 'react';
  2. import { ThemeContext } from './App';
  3. export default () => {
  4. const context = useContext(ThemeContext);
  5. return (
  6. <div>Example 组件:当前 theme 是:{ context }</div>
  7. )
  8. }
  9. 复制代码
注意事项

useContext必须是上下文对象本身的参数:

  • 正确: useContext(MyContext)
  • 不正确: useContext(MyContext.Consumer)
  • 不正确: useContext(MyContext.Provider)

useContext(MyContext)只允许您阅读上下文并订阅其更改。您仍然需要<MyContext.Provider>在树中使用以上内容来为此上下文提供值。

2、useReducer

语法

const [state, dispatch] = useReducer(reducer, initialArg, init);

useState 的替代方案。 接受类型为 (state, action) => newState 的reducer,并返回与 dispatch 方法配对的当前状态。

当你涉及多个子值的复杂 state(状态) 逻辑时,useReducer 通常优于 useState

用法

Example.js

  1. import React, { useReducer } from 'react';
  2. const initialState = {count: 0};
  3. function reducer(state, action) {
  4. switch (action.type) {
  5. case 'increment':
  6. return {count: state.count + 1};
  7. case 'decrement':
  8. return {count: state.count - 1};
  9. default:
  10. throw new Error();
  11. }
  12. }
  13. export default () => {
  14. // 使用 useReducer 函数创建状态 state 以及更新状态的 dispatch 函数
  15. const [state, dispatch] = useReducer(reducer, initialState);
  16. return (
  17. <>
  18. Count: {state.count}
  19. <br />
  20. <button onClick={() => dispatch({type: 'increment'})}>+</button>
  21. <button onClick={() => dispatch({type: 'decrement'})}>-</button>
  22. </>
  23. );
  24. }
  25. 复制代码
优化:延迟初始化

还可以懒惰地创建初始状态。为此,您可以将init函数作为第三个参数传递。初始状态将设置为 init(initialArg)

它允许您提取用于计算 reducer 外部的初始状态的逻辑。这对于稍后重置状态以响应操作也很方便:

Example.js

  1. import React, { useReducer } from 'react';
  2. function init(initialCount) {
  3. return {count: initialCount};
  4. }
  5. function reducer(state, action) {
  6. switch (action.type) {
  7. case 'increment':
  8. return {count: state.count + 1};
  9. case 'decrement':
  10. return {count: state.count - 1};
  11. case 'reset':
  12. return init(action.payload);
  13. default:
  14. throw new Error();
  15. }
  16. }
  17. export default ({initialCount = 0}) => {
  18. const [state, dispatch] = useReducer(reducer, initialCount, init);
  19. return (
  20. <>
  21. Count: {state.count}
  22. <br />
  23. <button
  24. onClick={() => dispatch({type: 'reset', payload: initialCount})}>
  25. Reset
  26. </button>
  27. <button onClick={() => dispatch({type: 'increment'})}>+</button>
  28. <button onClick={() => dispatch({type: 'decrement'})}>-</button>
  29. </>
  30. );
  31. }
  32. 复制代码
与 useState 的区别
  • state 状态值结构比较复杂时,使用 useReducer 更有优势。
  • 使用 useState 获取的 setState 方法更新数据时是异步的;而使用 useReducer 获取的 dispatch 方法更新数据是同步的。

针对第二点区别,我们可以演示一下: 在上面 useState 用法的例子中,我们新增一个 button

useState 中的 Example.js

  1. import React, { useState } from 'react';
  2. function Example() {
  3. // 声明一个名为“count”的新状态变量
  4. const [count, setCount] = useState(0);
  5. return (
  6. <div>
  7. <p>You clicked {count} times</p>
  8. <button onClick={() => setCount(count + 1)}>
  9. Click me
  10. </button>
  11. <button onClick={() => {
  12. setCount(count + 1);
  13. setCount(count + 1);
  14. }}>
  15. 测试能否连加两次
  16. </button>
  17. </div>
  18. );
  19. }
  20. export default Example;
  21. 复制代码

点击 测试能否连加两次 按钮,会发现,点击一次, count 还是只增加了 1,由此可见,useState 确实是 异步 更新数据;

在上面 useReducer 用法的例子中,我们新增一个 button: useReducer 中的 Example.js

  1. import React, { useReducer } from 'react';
  2. const initialState = {count: 0};
  3. function reducer(state, action) {
  4. switch (action.type) {
  5. case 'increment':
  6. return {count: state.count + 1};
  7. case 'decrement':
  8. return {count: state.count - 1};
  9. default:
  10. throw new Error();
  11. }
  12. }
  13. export default () => {
  14. // 使用 useReducer 函数创建状态 state 以及更新状态的 dispatch 函数
  15. const [state, dispatch] = useReducer(reducer, initialState);
  16. return (
  17. <>
  18. Count: {state.count}
  19. <br />
  20. <button onClick={() => dispatch({type: 'increment'})}>+</button>
  21. <button onClick={() => dispatch({type: 'decrement'})}>-</button>
  22. <button onClick={() => {
  23. dispatch({type: 'increment'});
  24. dispatch({type: 'increment'});
  25. }}>
  26. 测试能否连加两次
  27. </button>
  28. </>
  29. );
  30. }
  31. 复制代码

点击 测试能否连加两次 按钮,会发现,点击一次, count 增加了 2,由此可见,每次dispatch 一个 action 就会更新一次数据,useReducer 确实是 同步 更新数据;

3、useCallback

语法

const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);

返回值 memoizedCallback 是一个 memoized 回调。传递内联回调和一系列依赖项。useCallback将返回一个回忆的memoized版本,该版本仅在其中一个依赖项发生更改时才会更改。当将回调传递给依赖于引用相等性的优化子组件以防止不必要的渲染(例如shouldComponentUpdate)时,这非常有用。

这个 Hook 的 API 不能够一两句解释的清楚,建议看一下这篇文章:useHooks 第一期:聊聊 hooks 中的 useCallback。里面介绍的比较详细。

4、useMemo

语法

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

返回一个memoized值。 传递“创建”函数和依赖项数组。useMemo只会在其中一个依赖项发生更改时重新计算memoized值。此优化有助于避免在每个渲染上进行昂贵的计算。

useMemo在渲染过程中传递的函数会运行。不要做那些在渲染时通常不会做的事情。例如,副作用属于useEffect,而不是useMemo。

用法

useMemo 可以帮助我们优化子组件的渲染,比如这种场景: 在 A 组件中有两个子组件 B 和 C,当 A 组件中传给 B 的 props 发生变化时,A 组件状态会改变,重新渲染。此时 B 和 C 也都会重新渲染。其实这种情况是比较浪费资源的,现在我们就可以使用 useMemo 进行优化,B 组件用到的 props 变化时,只有 B 发生改变,而 C 却不会重新渲染。

例子:

ExampleA.js

  1. import React from 'react';
  2. export default ({ text }) => {
  3. console.log('Example A:', 'render');
  4. return <div>Example A 组件:{ text }</div>
  5. }
  6. 复制代码

ExampleB.js

  1. import React from 'react';
  2. export default ({ text }) => {
  3. console.log('Example B:', 'render');
  4. return <div>Example B 组件:{ text }</div>
  5. }
  6. 复制代码

App.js

  1. import React, { useState } from 'react';
  2. import ExampleA from './ExampleA';
  3. import ExampleB from './ExampleB';
  4. import './App.css';
  5. export default () => {
  6. const [a, setA] = useState('ExampleA');
  7. const [b, setB] = useState('ExampleB');
  8. return (
  9. <div>
  10. <ExampleA text={ a } />
  11. <ExampleB text={ b } />
  12. <br />
  13. <button onClick={ () => setA('修改后的 ExampleA') }>修改传给 ExampleA 的属性</button>
  14. &nbsp;&nbsp;&nbsp;&nbsp;
  15. <button onClick={ () => setB('修改后的 ExampleB') }>修改传给 ExampleB 的属性</button>
  16. </div>
  17. )
  18. }
  19. 复制代码

此时我们点击上面任意一个按钮,都会看到控制台打印了两条输出, A 和 B 组件都会被重新渲染。

现在我们使用 useMemo 进行优化

App.js

  1. import React, { useState, useMemo } from 'react';
  2. import ExampleA from './ExampleA';
  3. import ExampleB from './ExampleB';
  4. import './App.css';
  5. export default () => {
  6. const [a, setA] = useState('ExampleA');
  7. const [b, setB] = useState('ExampleB');
  8. + const exampleA = useMemo(() => <ExampleA />, [a]);
  9. + const exampleB = useMemo(() => <ExampleB />, [b]);
  10. return (
  11. <div>
  12. + {/* <ExampleA text={ a } />
  13. + <ExampleB text={ b } /> */}
  14. + { exampleA }
  15. + { exampleB }
  16. <br />
  17. <button onClick={ () => setA('修改后的 ExampleA') }>修改传给 ExampleA 的属性</button>
  18. &nbsp;&nbsp;&nbsp;&nbsp;
  19. <button onClick={ () => setB('修改后的 ExampleB') }>修改传给 ExampleB 的属性</button>
  20. </div>
  21. )
  22. }
  23. 复制代码

此时我们点击不同的按钮,控制台都只会打印一条输出,改变 a 或者 b,A 和 B 组件都只有一个会重新渲染。

5、useRef

语法

const refContainer = useRef(initialValue);

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传递的参数(initialValue)。返回的对象将存留在整个组件的生命周期中。

  • 从本质上讲,useRef就像一个“盒子”,可以在其.current财产中保持一个可变的价值。
  • useRef() Hooks 不仅适用于 DOM 引用。 “ref” 对象是一个通用容器,其 current 属性是可变的,可以保存任何值(可以是元素、对象、基本类型、甚至函数),类似于类上的实例属性。

注意:useRef() 比 ref 属性更有用。与在类中使用 instance(实例) 字段的方式类似,它可以 方便地保留任何可变值。

注意,内容更改时useRef 不会通知您。变异.current属性不会导致重新渲染。如果要在React将引用附加或分离到DOM节点时运行某些代码,则可能需要使用回调引用。

使用

下面这个例子中展示了可以在 useRef() 生成的 refcurrent 中存入元素、字符串

Example.js

  1. import React, { useRef, useState, useEffect } from 'react';
  2. export default () => {
  3. // 使用 useRef 创建 inputEl
  4. const inputEl = useRef(null);
  5. const [text, updateText] = useState('');
  6. // 使用 useRef 创建 textRef
  7. const textRef = useRef();
  8. useEffect(() => {
  9. // 将 text 值存入 textRef.current 中
  10. textRef.current = text;
  11. console.log('textRef.current:', textRef.current);
  12. });
  13. const onButtonClick = () => {
  14. // `current` points to the mounted text input element
  15. inputEl.current.value = "Hello, useRef";
  16. };
  17. return (
  18. <>
  19. {/* 保存 input 的 ref 到 inputEl */}
  20. <input ref={ inputEl } type="text" />
  21. <button onClick={ onButtonClick }>在 input 上展示文字</button>
  22. <br />
  23. <br />
  24. <input value={text} onChange={e => updateText(e.target.value)} />
  25. </>
  26. );
  27. }
  28. 复制代码

点击 在 input 上展示文字 按钮,就可以看到第一个 input 上出现 Hello, useRef;在第二个 input 中输入内容,可以看到控制台打印出对应的内容。

6、useLayoutEffect

语法

useLayoutEffect(() => { doSomething });

useEffect Hooks 类似,都是执行副作用操作。但是它是在所有 DOM 更新完成后触发。可以用来执行一些与布局相关的副作用,比如获取 DOM 元素宽高,窗口滚动距离等等。

进行副作用操作时尽量优先选择 useEffect,以免阻止视觉更新。与 DOM 无关的副作用操作请使用 useEffect

用法

用法与 useEffect 类似。

Example.js

  1. import React, { useRef, useState, useLayoutEffect } from 'react';
  2. export default () => {
  3. const divRef = useRef(null);
  4. const [height, setHeight] = useState(100);
  5. useLayoutEffect(() => {
  6. // DOM 更新完成后打印出 div 的高度
  7. console.log('useLayoutEffect: ', divRef.current.clientHeight);
  8. })
  9. return <>
  10. <div ref={ divRef } style={{ background: 'red', height: height }}>Hello</div>
  11. <button onClick={ () => setHeight(height + 50) }>改变 div 高度</button>
  12. </>
  13. }
  14. 复制代码

五、尝试编写自定义 Hooks

这里我们就仿照官方的 useReducer 做一个自定义的 Hooks

1、编写自定义 useReducer

src 目录下新建一个 useReducer.js 文件:

useReducer.js

  1. import React, { useState } from 'react';
  2. function useReducer(reducer, initialState) {
  3. const [state, setState] = useState(initialState);
  4. function dispatch(action) {
  5. const nextState = reducer(state, action);
  6. setState(nextState);
  7. }
  8. return [state, dispatch];
  9. }
  10. 复制代码

tip: Hooks 不仅可以在函数组件中使用,也可以在别的 Hooks 中进行使用。

2、使用自定义 useReducer

好了,自定义 useReducer 编写完成了,下面我们看一下能不能正常使用呢?

改写 Example 组件

Example.js

  1. import React from 'react';
  2. // 从自定义 useReducer 中引入
  3. import useReducer from './useReducer';
  4. const initialState = {count: 0};
  5. function reducer(state, action) {
  6. switch (action.type) {
  7. case 'increment':
  8. return {count: state.count + 1};
  9. case 'decrement':
  10. return {count: state.count - 1};
  11. default:
  12. throw new Error();
  13. }
  14. }
  15. export default () => {
  16. // 使用 useReducer 函数创建状态 state 以及更新状态的 dispatch 函数
  17. const [state, dispatch] = useReducer(reducer, initialState);
  18. return (
  19. <>
  20. Count: {state.count}
  21. <br />
  22. <button onClick={() => dispatch({type: 'increment'})}>+</button>
  23. <button onClick={() => dispatch({type: 'decrement'})}>-</button>
  24. </>
  25. );
  26. }
  27. 复制代码

五、Hooks 使用及编写规范

  • 不要从常规 JavaScript 函数调用 Hooks;
  • 不要在循环,条件或嵌套函数中调用 Hooks;
  • 必须在组件的顶层调用 Hooks;
  • 可以从 React 功能组件调用 Hooks;
  • 可以从自定义 Hooks 中调用 Hooks;
  • 自定义 Hooks 必须使用 use 开头,这是一种约定;

六、使用 React 提供的 ESLint 插件

根据上一段所写,在 React 中使用 Hooks 需要遵循一些特定规则。但是在代码的编写过程中,可能会忽略掉这些使用规则,从而导致出现一些不可控的错误。这种情况下,我们就可以使用 React 提供的 ESLint 插件:eslint-plugin-react-hooks。下面我们就看看如何使用吧。

安装 ESLint 插件

  1. $ npm install eslint-plugin-react-hooks --save
  2. 复制代码

在 .eslintrc 中使用插件

  1. // Your ESLint configuration
  2. {
  3. "plugins": [
  4. // ...
  5. "react-hooks"
  6. ],
  7. "rules": {
  8. // ...
  9. "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks
  10. "react-hooks/exhaustive-deps": "warn" // Checks effect dependencies
  11. }
  12. }
  13. 复制代码

七、参考文档

React 官网

React Hooks FAQ

转载于:https://juejin.im/post/5caaa8ffe51d452b2b027f8a

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/827137
推荐阅读
相关标签
  

闽ICP备14008679号