日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
一篇帶給你ReactHooks完全上手指南

簡介

只能在函數(shù)組件的頂級作用域使用;只能在函數(shù)組件或者其他 Hooks 中使用。

hooks 使用時(shí)必須確保:

  1. 所有 Hook 必須要被執(zhí)行到。
  2. 必須按順序執(zhí)行。

ESlint

使用 Hooks 的一些特性和要遵循某些規(guī)則。

React 官方提供了一個(gè) ESlint 插件,專門用來檢查 Hooks 是否正確被使用。

安裝插件:

npm install eslint-plugin-react-hooks --save-dev

在 ESLint 配置文件中加入兩個(gè)規(guī)則:rules-of-hooks exhaustive-deps。

{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
// 檢查 Hooks 的使用規(guī)則
"react-hooks/rules-of-hooks": "error",
// 檢查依賴項(xiàng)的聲明
"react-hooks/exhaustive-deps": "warn"
}
}

useState

import React, { userState } from 'react'
function Example() {
// 聲明一個(gè)叫count的state變量,初始值為0
// 可以使用setCount改變這個(gè)count
const [ count, setCount ] = useState(0)
return (

You clicked {count} times




);
}

useState 的入?yún)⒁部梢允且粋€(gè)函數(shù)。當(dāng)入?yún)⑹且粋€(gè)函數(shù)的時(shí)候,這個(gè)函數(shù)只會在這個(gè)組件初始化渲染的時(shí)候執(zhí)行。

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

setState 也可以接收一個(gè)函數(shù)作為參數(shù): setSomeState(prevState => {})。

// 常見寫法
const handleIncrement = useCallback(() => setCount(count + 1), [count])
// 下面這種性能更好些
// 不會每次在 count 變化時(shí)都使用新的。
// 從而接收這個(gè)函數(shù)的組件 props 就認(rèn)為沒有變化,避免可能的性能問題
const handleIncrement = useCallback(() => setCount(q => q + 1), [])

useEffect

useEffect 會在每次 DOM 渲染后執(zhí)行,不會阻塞頁面渲染。

在頁面更新后才會執(zhí)行。即:每次組件 render 后,判斷依賴并執(zhí)行。

它同時(shí)具備 componentDidMount 、 componentDidUpdate 和 componentWillUnmount 三個(gè)生命周期函數(shù)的執(zhí)行時(shí)機(jī)。

useEffect 共兩個(gè)參數(shù): callback 和 dependences 。規(guī)則如下:

  • dependences 不存在時(shí),默認(rèn)是所有的 state 和 props 。即:每次 render 之后都會執(zhí)行 callback。
  • dependences 存在時(shí), dependences 數(shù)組中的所有項(xiàng),只要任何一個(gè)有改變,在觸發(fā) componentDidUpdate 之后也會執(zhí)行 callback。
  • dependences 為空數(shù)組時(shí),表示不依賴任何的 state 和 props 。即: useEffect 只會在 componentDidMount 之后執(zhí)行一次。其后 state 或 props 觸發(fā)的 componentDidUpdate 后不會執(zhí)行 callback。
  • callback 可以有返回值。該返回值是一個(gè)函數(shù)。會在 componentWillUnmount 時(shí)自動(dòng)觸發(fā)執(zhí)行。

依賴項(xiàng)中定義的變量一定是會在回調(diào)函數(shù)中用到的,否則聲明依賴項(xiàng)其實(shí)是沒有意義的。

依賴項(xiàng)一般是一個(gè)常量數(shù)組,而不是一個(gè)變量。因?yàn)橐话阍趧?chuàng)建 callback 的時(shí)候,你其實(shí)非常清楚其中要用到哪些依賴項(xiàng)了。

React 會使用淺比較來對比依賴項(xiàng)是否發(fā)生了變化,所以要特別注意數(shù)組或者對象類型。

如果你是每次創(chuàng)建一個(gè)新對象,即使和之前的值是等價(jià)的,也會被認(rèn)為是依賴項(xiàng)發(fā)生了變化。這是一個(gè)剛開始使用 Hooks 時(shí)很容易導(dǎo)致 Bug 的地方。

在頁面更新之后會觸發(fā)這個(gè)方法 :

import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (

You clicked {count} times




);
}

如果想針對某一個(gè)數(shù)據(jù)的改變才調(diào)用這個(gè)方法,需要在后面指定一個(gè)數(shù)組,數(shù)組里面是需要更新的那個(gè)值,它變了就會觸發(fā)這個(gè)方法。數(shù)組可以傳多個(gè)值,一般會將 Effect 用到的所有 props 和 state 都傳進(jìn)去。

// class 組件做法
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
document.title = `You clicked ${this.state.count} times`
}
}
// 函數(shù)組件 hooks做法:只有 count 變化了才會打印出 aaa
userEffect(() => {
document.title = `You clicked ${count} times`
}, [count])

如果我們想只在 mounted 的時(shí)候觸發(fā)一次,那我們需要指定后面的為空數(shù)組,那么就只會觸發(fā)一次,適合我們做 ajax 請求。

userEffect(() => {
console.log('mounted')
}, [])

如果想在組件銷毀之前執(zhí)行,那么我們就需要在 useEffect 里 return 一個(gè)函數(shù)。

useEffect(() => {
console.log("mounted");
return () => {
console.log('unmounted')
}
}, []);

示例:在 componentDidMount 中訂閱某個(gè)功能,在 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'
}
}
// 函數(shù)組件 hooks寫法
function Test1(props) {
const [ isOnline, setIsOnline ] = useState(null)
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline)
}
ChatApi.subscribeToFriendStatus(props.friend.id, handleStatusChange)
// 返回一個(gè)函數(shù)來進(jìn)行額外的清理工作
return function cleanup() {
ChatApi.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange)
}
})
if (isOnline === null) {
return 'loading...'
}
return isOnline ? 'Online' : 'Offline'
}

useLayoutEffect

useLayoutEffect 的用法跟 useEffect 的用法是完全一樣的,它們之間的唯一區(qū)別就是執(zhí)行的時(shí)機(jī)。

useLayoutEffect 會阻塞頁面的渲染。會保證在頁面渲染前執(zhí)行,也就是說頁面渲染出來的是最終的結(jié)果。

如果使用 useEffect ,頁面很可能因?yàn)殇秩玖?次而出現(xiàn)抖動(dòng)。

絕大多數(shù)情況下,使用 useEffect 即可。

useContext

useContext 可以很方便的去訂閱 context 的改變,并在合適的時(shí)候重新渲染組件。

接收一個(gè) context 對象(React.createContext 的返回值)并返回該 context 的當(dāng)前值。

context 基本示例:

// 因?yàn)樽嫦冉M件和子孫組件都用到這個(gè)ThemeContext,
// 可以將其放在一個(gè)單獨(dú)的js文件中,方便不同的組件引入
const ThemeContext = React.createContext('light')
class App extends React.Component {
render() {
return (



)
}
}
// 中間層組件
function Toolbar(props) {
return (



)
}
class ThemedButton extends React.Component {
// 通過定義靜態(tài)屬性 contextType 來訂閱
static contextType = ThemeContext
render() {
return

針對函數(shù)組件的訂閱方式:

function ThemedButton() {
// 通過定義 Consumer 來訂閱
return (

{ value =>

使用 useContext 來訂閱:

function ThemedButton() {
const value = useContext(ThemeContext)
return

在需要訂閱多個(gè) context 的時(shí)候,對比:

// 傳統(tǒng)的實(shí)現(xiàn)方法
function HeaderBar() {
return (

{user =>

{notification =>

Welcome back, {user.name}!
You have {notifications.length} notifications.

}

}

)
}
// 使用 useContext
function HeaderBar() {
const user = useContext(CurrentUser)
const notifications = useContext(Notifications)
return (

Welcome back, {use.name}!
You have {notifications.length} notifications.

)
}

useReducer

useReducer 用法跟 Redux 非常相似,當(dāng) state 的計(jì)算邏輯比較復(fù)雜又或者需要根據(jù)以前的值來計(jì)算時(shí),使用這種 Hook 比 useState 會更好。

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}




)
}

結(jié)合 context API,我們可以模擬 Redux 的操作:

const TodosDispatch = React.createContext(null)
const TodosState = React.createContext(null)
function TodosApp() {
const [todos, dispatch] = useReducer(todosReducer)
return (





)
}
function DeepChild(props) {
const dispatch = useContext(TodosDispatch)
const todos = useContext(TodosState)
function handleClick() {
dispatch({ type: 'add', text: 'hello' })
}
return (
<>
{todos}


)
}

useCallback / useMemo / React.memo

  • useCallback 和 useMemo 設(shè)計(jì)的初衷是用來做性能優(yōu)化的。
  • useCallback 緩存的是方法的引用。
  • useMemo 緩存的則是方法的返回值。
  • 使用場景是減少不必要的子組件渲染。
// useCallback
function Foo() {
const [ count, setCount ] = useState(0)
const memoizedHandleClick = useCallback(
() => console.log(`Click happened with dependency: ${count}`), [count],
)
return
}
// useMemo
function Parent({a, b}) {
// 當(dāng) a 改變時(shí)才會重新渲染
const child1 = useMemo(() => , [a])
// 當(dāng) b 改變時(shí)才會重新渲染
const child2 = useMemo(() => , [b])
return (
<>
{child1}
{child2}

)
}

若要實(shí)現(xiàn) class 組件的 shouldComponentUpdate 方法,可以使用 React.memo 方法。

區(qū)別是它只能比較 props ,不會比較 state。

const Parent = React.memo(({ a, b}) => {
// 當(dāng) a 改變時(shí)才會重新渲染
const child1 = useMemo(() => , [a])
// 當(dāng) b 改變時(shí)才會重新渲染
const child2 = useMemo(() => , [b])
return (
<>
{child1}
{child2}

)
})

return

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

useRef 值的變化不會引起組件重繪,可以存一些跟界面顯示無關(guān)的變量。

函數(shù)式組件不能設(shè)置 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 (


我們都是中國人

)
}
/* eslint-disable react/display-name */
// const Test = forwardRef((props, ref) => (
//

//
test module

// {props.children}
//

// ))
const Test = forwardRef(function Test(props, ref) {
const [count, setCount] = useState(1)

useEffect(() => {
ref.current = {
count,
setCount
}
})
return (

當(dāng)前count:{count}



)
})

自定義hook

自定義 Hook 是一個(gè)函數(shù),但是名稱必須是以 use 開頭,函數(shù)內(nèi)部可以調(diào)用其他的 Hook。

自定義 Hook 是一種自然遵循 Hook 設(shè)計(jì)的約定,而并不是 React 的特性。

跟普通的 hook 一樣,只能在函數(shù)組件或者其他 Hooks 中使用。


文章題目:一篇帶給你ReactHooks完全上手指南
本文URL:http://m.5511xx.com/article/djehcsh.html