Hooks
React Hooks 是 React 在16.8版本中更新的新特性,在 React 中一直提倡使用函数组件,老版本中函数组件没有组件实例,没有 state,没有生命周期函数,导致很多情况不得不使用类组件,但是 Hooks 出来后我们可以在不使用类组件的情况下使用state及其他React特性
一、useState
- useState的基本使用
这是官方的一个基本使用示例,import引入 useState 函数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>)}
调用函数时传入初始化的值
函数返回一个数组: 一个为初始化的state, 一个为更新state函数
最后在其他地方使用state, 或者调用更新state函数
注意: 更新state的函数会直接替换state,而不是像以前setState会合并新老state
2.使用push, pop, splice等直接更改数组对象的坑
因为useState的更新函数会直接替换老的state,所以我们在对对象或者数组的state做增删的时候不能像以前直接数组使用push, pop, splice等直接改变数组的方法
错误示例: ```javascript import React, { useState } from “react”;
function Comment() { const [counts, setCounts] = useState([1, 2]); const handleAdd = () => { const randomCount = Math.round(Math.random()*100) // 在此地方我们使用push增加一个随机数,程序报错 setCounts(counts.push(randomCount)) } return (
export default Comment;
正确的方法应该是使用数组解构成一个新数组,在数组后面加上我们新增的随机项,使用filter数组过滤方法来实现我们删除其中项的操作。<br />数组新增项:```javascriptimport React, { useState } from "react";function Comment() {const [counts, setCounts] = useState([1, 2]);const handleAdd = () => {const randomCount = Math.round(Math.random()*100)// 在此我们用数组结构生成新数组,并在后面加上我们要新增的随机数setCounts([...counts,randomCount])}return (<div>{counts.map((count) => (<div key={count}>{count}</div>))}<button onClick={handleAdd}>增加</button></div>);}export default Comment;
删除其中项:
import React, { useState } from 'react';function Comment() {const [counts, setCounts] = useState([1, 2, 3, 4]);const handleDel = () => {// 使用数组的filtler方法,过滤删除其中不需要的项setCounts(counts.filter((count, index) => index !== counts.length - 1))}return (<div>{counts.map((count) => (<div key={count}>{count}</div>))}<button onClick={handleDel}>删除</button></div>)}export default Comment;
此外还有一个方法是类似以前使用redux的reducer中对老的数组对象做深拷贝,然后做增删操作,最后返回
import React, { useState } from "react";function Comment() {const [counts, setCounts] = useState([1, 2]);const handleAdd = () => {setCounts(counts => {const randomCount = Math.round(Math.random()*100)// 简单使用JSON.parse及JSON.stringify深拷贝一个新的数组和对象(实际项目中建议自己写递归深拷贝函数),然后对其操作返回let newCounts = JSON.parse(JSON.stringify(counts))newCounts.push(randomCount)return newCounts})}return (<div>{counts.map((count) => (<div key={count}>{count}</div>))}<button onClick={handleAdd}>增加</button></div>);}export default Comment;
- 每次渲染都是独立闭包的坑
当我们先执行异步增加函数(handleSyncAdd),再执行同步函数(handleAdd),同步执行完毕再执行异步时,异步函数里面的count为之前执行时闭包里面的值(0),错误示例: ```javascript import React, { useState } from “react”;
function Comment() { const [count, setCount] = useState(0); const handleAdd = () => setCount(count + 1); const handleSyncAdd = () => { setTimeout(() => { // 获取的是闭包中的state setCount(count + 1); }, 1000); }; return (
{count}
export default Comment;
这种情况我们要使用回调式函数更新<br />正确示例:```javascriptimport React, { useState } from "react";function Comment() {const [count, setCount] = useState(0);const handleAdd = () => setCount(count + 1);const handleSyncAdd = () => {setTimeout(() => {// 改成回调函数更新,每次回调函数执行时会接收之前的state,而不是闭包中的statesetCount(count => count + 1);}, 1000);};return (<div><p>{count}</p><button onClick={handleAdd}>增加</button><button onClick={handleSyncAdd}>异步增加</button></div>);}export default Comment;
二、useEffect
effect (副作用),可以理解为我们在使用类组件时的生命周期函数
useEffect 可以实现我们类组件中的componentDidMount、ComponentDidUpdate和componentWillUnmount的功能呢,只不过被合并成为一个API
与componentDidMount或者componentDidUpdate不同的是,使用useEffect不会阻塞浏览器更新屏幕,这让你的应用看起来响应更快。大多数情况下,effect不需要同步执行。在个别情况下(例如测量布局),有单独的useLayoutEffect供使用,其API与useEffect相同。
1.useEffect实现componentDidMount 及 componentDidUpdate
直接使用useEffect传入一个回调函数,会在组件初次渲染及每次更新渲染时执行
import React, { useState, useEffect } from 'react'function Parent() {const [count, setCount] = useState(0)const handleAdd = () => setCount(count + 1)// 使用useEffect传入一个回调函数使用类组件componentDidMount和componentDidUpdate功能useEffect(() => {console.log('parent effect');})return (<div>parent, {count}<button onClick={handleAdd}>增加</button></div>)}export default Parent
- 使用useEffect 实现componentDidMount功能
很多时候我们只需要组件初次加载做一些事,如ajax获取数据等,我们只需要在useEfffect的第二个参数传入一个空数组,这个数组的意思是数组里面监听的值发生更新update时执行effect ```javascript import React, { useState, useEffect } from ‘react’
function Parent() { const [count, setCount] = useState(0) const handleAdd = () => setCount(count + 1) // 第二个参数传入空数组,不需要根据其他值执行effect,只会在组件初次加载执行 useEffect(() => { console.log(‘parent didMount’); }, []) return (
export default Parent
也可以在第二个数组中传入值,表明根据这个值update时执行effect```javascriptimport React, { useState, useEffect } from 'react'function Parent() {const [count, setCount] = useState(0)const handleAdd = () => setCount(count + 1)// 第二个参数传入含有count的数组,count更新时执行effectuseEffect(() => {console.log('count update');}, [count])return (<div>parent, {count}<button onClick={handleAdd}>增加</button></div>)}export default Parent
3.使用useEffect实现componentWillUnmout功能
在项目中我们需要在组件卸载时清除定时器、监听等,使用useEffect返回一个函数,这个函数会在组件卸载时调用完成componentWillUnmout的功能
import React, { useState, useEffect } from 'react'function Parent() {const [count, setCount] = useState(0)const handleAdd = () => setCount(count + 1)// 在useEffect中返回一个函数完成componentWillUnmoun的功能useEffect(() => {console.log('component mount');return () => {console.log('component unmount');}})return (<div>parent, {count}<button onClick={handleAdd}>增加</button></div>)}export default Parent
三、useMemo
useMemo可以初略理解为Vue中的计算属性,在依赖的某一属性改变的时候自动执行里面的计算并返回最终的值(并缓存,依赖性改变时才重新计算),对于性能消耗比较大的一定要使用useMemo不然每次更新都会重新计算。
示例:
import React, {useState, useMemo} from 'react'function Parent() {const [count, setCount] = useState(0);const [price, setPrice] = useState(1);const handleCountAdd = () => setCount(count + 1);cosnt handlePriceAdd = () => setprice(price + 1);// 使用useMemo在count 和 price 改变时自动计算总价const all = useMemo(() => count * price, [count, price])return (<div>parent, {count}<button onClick = {handleCountAdd}>增加数量</button><button onClick = {handlePriceAdd}>增加数量</button><p>count: {count}, price: {price} all: {all}</p></div>)}export default Parent
四、useCallbacK
useCallback不同于useMemo的是,useMemo是缓存的值,useCallback是缓存的函数,父组件给子组件传递参数为普通函数时,父组件每次更新子组件都会更新,但是大部分情况子组件更新是没有必要的,这时候我们用useCallback来定义函数,并把这个函数传递给子组件,子组件就会根据依赖再更新了。
示例:
import React, { useState, useCallback, useEffect} from 'react';function Parent() {const [count, setCount] = useState(1);const [val, setVal] = useState('');const callback = useCallback(() => {return count;}, [count])return (<div><h4>{count}</h4><Child callback={callback} /><div><button>+</button><input value = {val} onChange={event => setVal(event.target.value)} /></div></div>)}function Child() {const [count, setCount] = useState(() => callback());useEffect(() => {console.log(123);setCount(callback());}, [callbakc]);return <div>{count}</div>}
五、useReducer
useReducer 和 redux中reducer类似, useState的替代方案,它接收一个形如(state, action)=> newState 的reducer, 并返回当前的state以及与其配套的dispatch方法。(如果你熟悉Redux的话,就知道它如何工作了)。
在某些场景下,useReducer会比useState更适用,例如state逻辑较复杂且包含多个子值,或者下一个state依赖于之前的state等。并且,使用useReducer还能给那些会触发深更新的组件做性能优化,因为你可以向子组件传递dispatch而不是回调函数。
import React, { useReducer } from 'react'function Parent() {const reducer = ( state, action) => {switch (action.type) {case 'add':return { count: state.count + 1}case 'reduce':return { count: state.count - 1}default:throw new Error()}}let initialStae = 0;const init = (initialState) => ({ count: initialState })// 第三个参数为惰性初始化函数,可以用来进行复杂计算返回最终的initialState,如果initialState比较简单可以忽略此参数const [state, dispatch] = useReducer(reducer, initialSate, init)return (<div><p>{state.count}</p><button onClick = {() => dispatch({type: 'add'})}>add</button><button onClick = {() => dispatch({type: 'reduce'}) }>reduce</button></div>)}export default Parent
六、useContext
usecontext可以实现类似react-redux插件功能, 上层组件使用createContext创建一个context, 并使用
示例:
import React, { useState, createContext, useContext} from "react";// 使用createContext 来创建一个contextconst CounterContext = createContext();function Parent() {const [count, setCount] = useState(0);return (// 父组件使用<MyContext.Provider>传递context<CounterContext.Provider value = {{count, setCount}} >{count}<Child /></CounterContext.Provider>)}function Child() {// 子组件使用useContext接收contextconst { count, setCount } = useContext(CounterContext);return (<div><button onClick={() => setCount(count + 1)}>add</button></div>)}export default Parent
七、useLayoutEffect
其使用方法与useEffect一样,但它会在有的DOM变更之后同步调用effect.可以使用它来读取DOM布局并同步触发重渲染。在浏览器执行绘制之前,useLayoutEffect内部的更新计划将被同步刷新。useEffect为异步,useLayoutEffect为同步,推荐你一开始先用useEffect,只有当它出问题的时候再尝试使用useLayoutEffect
八、useRef
React Hooks中用来获取DOM节点
示例:
import React, { useRef } from 'react';function Parent() {// 使用userRef创建一个ref, 并在标签中绑定到ref属性上const pRef = useRef(null)return (<div><p ref={pRef}>Content</p></div>)}export default Parent;
九、自定义Hooks
自定义Hooks可以实现逻辑复用等,在多个组件中可以复用我们自定义的Hooks,并且里面的状态是独立的,自定义Hooks我们一般按照规则以use开头定义
示例:
import React, { useState } from 'react'// 自定义useCount 的Hooksfunction useCount() {const [count, setCount] = useState(0);return {count, setCount};}function Parent() {// 父组件使用,状态独立const {count , setCount } = useCount()return (<div><p>parent</p><p>{count}</p><button onClick= {() => setCount(count + 1)}> add </button><Child /></div>)}function Child() {// 子组件的使用,状态独立const {count, setCount} = useCount()return (<div><p>child</p><h1> {count} </h1><button onClick={() => setCount(count + 2)}>add</button></div>)}export default Parent;
以上就是React Hooks的基本使用详解, 基本可以用React Hooks覆盖我们类组件的使用,官方也更推荐我们使用React Hooks来开发新项目!
