React hooks笔记

hooks是函数组件独有的。在不编写class的情况下使用state以及其他的React特性

React基础知识参考:React笔记

只能在函数组件的顶级作用域使用;只能在函数组件或者其他 Hooks 中使用。

第一,所有 Hook 必须要被执行到。第二,必须按顺序执行。

ESlint

使用 Hooks 的一些特性和要遵循某些规则。
React官方提供了一个ESlint插件,专门用来检查Hooks是否正确被使用。

  • 安装插件:npm install eslint-plugin-react-hooks --save-dev

  • ESLint 配置文件中加入两个规则:rules-of-hooksexhaustive-deps

{ "plugins": [ // ... "react-hooks" ], "rules": { // ... // 检查 Hooks 的使用规则 "react-hooks/rules-of-hooks": "error", // 检查依赖项的声明 "react-hooks/exhaustive-deps": "warn" } }

useState

import React, { userState } from 'react' function Example() { // 声明一个叫count的state变量,初始值为0 // 可以使用setCount改变这个count const [ count, setCount ] = useState(0) return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }

useState的入参也可以是一个函数。当入参是一个函数的时候,这个函数只会在这个组件初始化渲染的时候执行

const [ count, setCount ] = useState(() => { const initialCount = someExpensiveComputation(props) return initialCount })

setState也可以接收一个函数作为参数:setSomeState(prevState => {})

// 常见写法 const handleIncrement = useCallback(() => setCount(count + 1), [count]) // 下面这种性能更好些 // 不会每次在 count 变化时都使用新的。从而接收这个函数的组件 props 就认为没有变化,避免可能的性能问题 const handleIncrement = useCallback(() => setCount(q => q + 1), [])

useEffect

useEffect会在每次DOM渲染后执行,不会阻塞页面渲染。
在页面更新后才会执行。即:每次组件render后,判断依赖并执行。

它同时具备componentDidMountcomponentDidUpdatecomponentWillUnmount三个生命周期函数的执行时机。

useEffect共两个参数:callbackdependences。规则如下

  • dependences不存在时,默认是所有的stateprops。即:每次render之后都会执行callback
  • dependences存在时,dependences数组中的所有项,只要任何一个有改变,在触发componentDidUpdate之后也会执行callback
  • dependences为空数组时,表示不依赖任何的stateprops。即:useEffect只会在componentDidMount之后执行一次。其后stateprops触发的componentDidUpdate不会执行callback
  • callback可以有返回值。该返回值是一个函数。会在componentWillUnmount时自动触发执行

依赖项中定义的变量一定是会在回调函数中用到的,否则声明依赖项其实是没有意义的。

依赖项一般是一个常量数组,而不是一个变量。因为一般在创建 callback 的时候,你其实非常清楚其中要用到哪些依赖项了。

React 会使用浅比较来对比依赖项是否发生了变化,所以要特别注意数组或者对象类型。
如果你是每次创建一个新对象,即使和之前的值是等价的,也会被认为是依赖项发生了变化。
这是一个刚开始使用 Hooks 时很容易导致 Bug 的地方。

  • 在页面更新之后会触发这个方法
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
  • 如果想针对某一个数据的改变才调用这个方法,需要在后面指定一个数组,数组里面是需要更新的那个值,它变了就会触发这个方法。数组可以传多个值,一般会将Effect用到的所有propsstate都传进去
// class 组件做法 componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { document.title = `You clicked ${this.state.count} times` } } // 函数组件 hooks做法:只有 count 变化了才会打印出 aaa userEffect(() => { document.title = `You clicked ${count} times` }, [count])
  • 如果我们想只在mounted的时候触发一次,那我们需要指定后面的为空数组,那么就只会触发一次,适合我们做ajax请求
userEffect(() => { console.log('mounted') }, [])
  • 如果想在组件销毁之前执行,那么我们就需要在useEffectreturn一个函数
useEffect(() => { console.log("mounted"); return () => { console.log('unmounted') } }, []);

示例一:在componentDidMount中订阅某个功能,在componentWillUnmount中取消订阅

// class组件写法 class Test extends React.Component { constructor(props) { super(props) this.state = { isOnline: null } this.handleStatusChange = this.handleStatusChange.bind(this) } componentDidMount() { ChatApi.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ) } componentWillUnmount() { ChatApi.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ) } handleStatusChange(status) { this.setState({ isOnline: status.isOnline }) } render() { if (this.state.isOnline === null) { return 'loading...' } return this.state.isOnline ? 'Online' : 'Offline' } } // 函数组件 hooks写法 function Test1(props) { const [ isOnline, setIsOnline ] = useState(null) useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline) } ChatApi.subscribeToFriendStatus(props.friend.id, handleStatusChange) // 返回一个函数来进行额外的清理工作 return function cleanup() { ChatApi.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange) } }) if (isOnline === null) { return 'loading...' } return isOnline ? 'Online' : 'Offline' }

useLayoutEffect

useLayoutEffect的用法跟useEffect的用法是完全一样的,它们之间的唯一区别就是执行的时机

useLayoutEffect会阻塞页面的渲染。会保证在页面渲染前执行,也就是说页面渲染出来的是最终的结果。

如果使用useEffect,页面很可能因为渲染了2次而出现抖动

绝大多数情况下,useEffect是更好的选择

useContext

useContext可以很方便的去订阅context的改变,并在合适的时候重新渲染组件。

接收一个 context 对象(React.createContext 的返回值)并返回该 context 的当前值。

  • context基本示例
// 因为祖先组件和子孙组件都用到这个ThemeContext, // 可以将其放在一个单独的js文件中,方便不同的组件引入 const ThemeContext = React.createContext('light') class App extends React.Component { render() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext> ) } } // 中间层组件 function Toolbar(props) { return ( <div> <ThemedButton /> </div> ) } class ThemedButton extends React.Component { // 通过定义静态属性 contextType 来订阅 static contextType = ThemeContext render() { return <Button theme={this.context} /> } }
  • 针对函数组件的订阅方式
function ThemedButton() { // 通过定义 Consumer 来订阅 return ( <ThemeContext.Consumer> { value => <Button theme={value} />} </ThemeContext.Consumer> ) }
  • 使用useContext来订阅
function ThemedButton() { const value = useContext(ThemeContext) return <Button theme={value} /> }
  • 在需要订阅多个context的时候,对比
// 传统的实现方法 function HeaderBar() { return ( <CurrentUser.Consumer> {user => <Notification.Consumer> {notification => <header> Welcome back, {user.name}! You have {notifications.length} notifications. </header> } </Notification.Consumer> } </CurrentUser.Consumer> ) } // 使用 useContext function HeaderBar() { const user = useContext(CurrentUser) const notifications = useContext(Notifications) return ( <header> Welcome back, {use.name}! You have {notifications.length} notifications. </header> ) }

useReducer

useReducer用法跟Redux非常相似,当state的计算逻辑比较复杂又或者需要根据以前的值来计算时,使用这种HookuseState会更好

function init(initialCount) { return { count: initialCount } } function reducer(state, action) { switch(action.type) { case 'increment': return { count: state.count + 1 } case 'decrement': return { count: state.count - 1 } case 'reset': return init(action.payload) default: throw new Error() } } function Counter({ initialCount }) { const [state, dispatch] = useReducer(reducer, initialCount, init) return ( <> Count: {state.count} <button onClick={() => dispatch({ type: 'reset', payload: initialCount })}>Reset</button> <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </> ) }

结合context API,我们可以模拟Redux的操作

const TodosDispatch = React.createContext(null) const TodosState = React.createContext(null) function TodosApp() { const [todos, dispatch] = useReducer(todosReducer) return ( <TodosDispatch.Provider value={dispatch}> <TodosState.Provider value={todos}> <DeepTree todos={todos} /> </TodosState.Provider> </TodosDispatch.Provider> ) } function DeepChild(props) { const dispatch = useContext(TodosDispatch) const todos = useContext(TodosState) function handleClick() { dispatch({ type: 'add', text: 'hello' }) } return ( <> {todos} <button onClick={handleClikc}>Add Todo</button> </> ) }

useCallback / useMemo / React.memo

useCallbackuseMemo设计的初衷是用来做性能优化的

useCallback缓存的是方法的引用
useMemo缓存的则是方法的返回值
使用场景是减少不必要的子组件渲染

// useCallback function Foo() { const [ count, setCount ] = useState(0) const memoizedHandleClick = useCallback( () => console.log(`Click happened with dependency: ${count}`), [count], ) return <Button onClick={memoizedHandleClick}>Click Me</Button> } // useMemo function Parent({a, b}) { // 当 a 改变时才会重新渲染 const child1 = useMemo(() => <Child1 a={a} />, [a]) // 当 b 改变时才会重新渲染 const child2 = useMemo(() => <Child2 b={b} />, [b]) return ( <> {child1} {child2} </> ) }

若要实现class组件的shouldComponentUpdate方法,可以使用React.memo方法。
区别是它只能比较props,不会比较state

const Parent = React.memo(({ a, b}) => { // 当 a 改变时才会重新渲染 const child1 = useMemo(() => <Child1 a={a} />, [a]) // 当 b 改变时才会重新渲染 const child2 = useMemo(() => <Child2 b={b} />, [b]) return ( <> {child1} {child2} </> ) })

useRef

// class组件获取ref class Test extends React.Component { constructor(props) { super(props) this.myRef = React.createRef() } componentDidMount() { this.myRef.current.focus() } render() { return <input ref={this.myRef} type="text" /> } } // 使用useRef function Test() { const myRef = useRef(null) useEffect(() => { myRef.current.focus() }, []) return <input ref={myRef} type="text" /> }

useRef值的变化不会引起组件重绘,可以存一些跟界面显示无关的变量

函数式组件不能设置ref,想保存其中的某些值,可以通过React.forwardRef

import React, { useState, useEffect, useRef, forwardRef } from 'react' export default function Home(props) { const testRef = useRef(null) useEffect(() => { console.log(testRef.current) }, []) return ( <div> <button onClick={() => testRef.current?.setCount(8)}>add parent</button> <Test ref={testRef}>我们都是中国人</Test> </div> ) } /* eslint-disable react/display-name */ // const Test = forwardRef((props, ref) => ( // <div ref={ref}> // <div>test module</div> // {props.children} // </div> // )) const Test = forwardRef(function Test(props, ref) { const [count, setCount] = useState(1) useEffect(() => { ref.current = { count, setCount } }) return ( <div> <div>当前count:{count}</div> <button onClick={() => setCount(count + 1)}>add</button> </div> ) })

自定义hook

  • 示例
// hooks import { useState, useCallback } from 'react' export default const useAsync = (asyncFunc) => { // 设置三个异步逻辑相关的 state const [data, setData] = useState(null) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) // 定义一个 callback 用于执行异步逻辑 const execute = useCallback(() => { // 请求开始时,设置 loading 为 true,清除已有数据和 error 状态 setLoading(true) setData(null) setError(null) return asyncFunc().then(res => { // 请求成功,将数据写进 state,设置 loading 为 false setData(res) setLoading(false) }).catch(err => { // 请求失败,设置 loading 为 false,并设置错误状态 setError(error) setLoading(false) }) }, [asyncFunc]) return { execute, loading, data, error } } // 组件中使用 import React from 'react' import useAsync from './useAsync' export default function UserList(props) { // 通过 useAsync 这个函数,只需要提供异步逻辑的实现 const { execute: fetchUsers, data: users, loading, error, } = useAsync(async () => { const res = await fetch('http://xxx/xxx') const json = await res.json return json.data }) return ( // 根据状态渲染 UI... ) }
  • useUpdate更新时执行
import { useRef, useEffect } from 'react' export default function useUpdate( callback = () => {}, dependences, initialData = false ) { const isInitialMount = useRef(true) useEffect(() => { // 第一次,也就是mount阶段 不执行onChange,只有后续更新的时候才调用 // 因为在页面中,一般mount阶段会写请求数据之类的操作 if (isInitialMount.current && !initialData) { isInitialMount.current = false } else { callback() } }, dependences) } // 使用示例 // useUpdate(() => { // console.log(count) // }, [count])
  • useForceUpdate强制更新
import { useReducer, useLayoutEffect, useRef } from 'react' export default function useForceUpdate() { // 函数组件没有forceUpdate,用这种方法代替 const [ignored, forceUpdate] = useReducer(x => x + 1, 0) const resolveRef = useRef(null) useLayoutEffect(() => { resolveRef.current && resolveRef.current() }, [ignored]) const promise = () => { return new Promise((resolve, reject) => { forceUpdate() resolveRef.current = resolve }) } return { forceUpdate: promise } } // 使用示例 - 函数组件没有forceUpdate,用这种方法代替 // const { forceUpdate } = useForceUpdate() // useEffect(() => { // forceUpdate().then(() => { // // 得等到上一次渲染完成后,才能拿到最新的宽度和高度 // chart?.forceFit() // }) // }, [count])
  • usePrevious记录上一次的值
import { useEffect, useRef } from 'react' export default function usePrevious(value) { const ref = useRef() useEffect(() => { ref.current = value }, [value]) return ref.current } // 使用示例 // const [count, setCount] = useState(1) // const preCount = usePrevious(count)
  • 监听滚动位置
// hooks import { useState, useEffect } from 'react' // 获取横向,纵向滚动条位置 export default const getPosition = () => { return { x: document.body.scrollLeft, y: document.body.scrollTop, } } const useScroll = () => { // 定一个 position 这个 state 保存滚动条位置 const [position, setPosition] = useState(getPosition()) useEffect(() => { const handler = () => { setPosition(getPosition()) } // 监听 scroll 事件,更新滚动条位置 document.addEventListener('scroll', handler) return () => { // 组件销毁时,取消事件监听 document.removeEventListener('scroll', handler) } }, []) return position } // 组件 - 返回顶部功能 import React, { useCallback } from 'react' import useScroll from './useScroll' export default function ScrollTop (props) { const { y } = useScroll() const goTop = useCallback(() => { document.body.scrollTop = 0 }, []) const style = { position: 'fixed', right: '10px', bottom: '10px', } // 当滚动条位置纵向超过300时,显示返回顶部按钮。否则不渲染任何UI if (y <= 300) return null return ( <button onClick={goTop} style={style}> Back to Top </button> ) }

创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: