做網站專家一個網站推廣
一、什么是Hooks
Hooks 是 React 16.8 的新增特性。在不編寫 class 的情況下使用 state 以及其他的 React 特性。Hooks 是一種在函數式組件中使用有狀態(tài)函數的方法。
二、類組件
componentDidMount
、componentDidUpdate
?和?componentWillUnmount
?這三個函數的組合。
三、常用的Hook Api
- useState
- useEffect
- useContext
- useCallback
- useMemo
- useRef
- useImperativeHandle
1、useState使用
import React, { useState } from 'react';2 import {3 SafeAreaView,4 Text,5 TouchableOpacity6 } from 'react-native';7 import Constants from './expand/dao/Constants';8 import { post } from './expand/dao/HiNet';9 export default (props: any) => {10 const [msg, setMsg] = useState('');11 const doFetch = () => {12 const formData = new FormData();13 formData.append("requestPrams", 'RN');14 post(Constants.test.api)(formData)().then(result => {15 setMsg(JSON.stringify(result));16 }).catch(e => {17 console.log(e);18 setMsg(JSON.stringify(e));19 })20 }21 return (22 <SafeAreaView>23 <TouchableOpacity onPress={doFetch}>24 <Text>加載</Text>25 </TouchableOpacity>26 <Text>{msg}</Text>27 </SafeAreaView>28 );29 };
從上述代碼中我們不難看出,在React Native中使用State Hook
的主要步驟:
- 導入
useState
:import React, { useState } from 'react';
- 通過
useState
定義state:const [msg, setMsg] = useState('');
- msg是定義的state中一個變量,setMsg是用來修改msg變量的關聯函數,它的格式是
set+變量名首字母大寫
- msg是定義的state中一個變量,setMsg是用來修改msg變量的關聯函數,它的格式是
- 修改狀態(tài):通過前面定義的關聯函數
setMsg
修改即可setMsg(JSON.stringify(result));
State Hook
的作用范圍:因為Hooks只能應用與函數式組件,所以通過它聲明的state的作用范圍是函數內。
Hook 簡介 – React2、useEffect使用
import React, { useState, useEffect } from 'react';
import {SafeAreaView,StyleSheet,Text,TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';
export default (props: { navigation: any }) => {const [msg, setMsg] = useState('');useEffect(() => {//對應componentDidUpdatefunction handleStatusChange(status: any) {console.log(status);}const timer = setTimeout(() => {doFetch();}, 2000);// 對應componentWillUnmountreturn function cleanup() {timer && clearTimeout(timer);};});const doFetch = () => {const formData = new FormData();formData.append("requestPrams", 'RN');post(Constants.test.api)(formData)().then(result => {setMsg(JSON.stringify(result));}).catch(e => {console.log(e);setMsg(JSON.stringify(e));})}return (<SafeAreaView><TouchableOpacity onPress={doFetch}><Text>加載</Text></TouchableOpacity><Text>{msg}</Text></SafeAreaView>);
};
- 導入
useEffect
:import React, { useState,useEffect } from 'react';
- 使用
useEffect
來實現不同生命周期函數的hooks:- 直接寫在
useEffect(() => {}
一層的會在組件裝載時調用,對應componentDidMount handleStatusChange
對應componentDidUpdate
cleanup
對應componentWillUnmount
在組件卸載時調
- 直接寫在
3、useContext使用
const value = useContext(MyContext);
接收一個 context 對象(React.createContext
?的返回值)并返回該 context 的當前值。當前的 context 值由上層組件中距離當前組件最近的?<MyContext.Provider>
?的?value
?prop 決定。
當組件上層最近的?<MyContext.Provider>
?更新時,該 Hook 會觸發(fā)重渲染,并使用最新傳遞給?MyContext
?provider 的 context?value
?值。即使祖先使用?React.memo?或?shouldComponentUpdate,也會在組件本身使用?useContext
?時重新渲染。
4、useCallback使用
const memoizedCallback = useCallback(() => {doSomething(a, b);},[a, b],
);
把內聯回調函數及依賴項數組作為參數傳入?useCallback
,它將返回該回調函數的 memoized 版本,該回調函數僅在某個依賴項改變時才會更新。當你把回調函數傳遞給經過優(yōu)化的并使用引用相等性去避免非必要渲染(例如?shouldComponentUpdate
)的子組件時,它將非常有用。
useCallback(fn, deps)
?相當于?useMemo(() => fn, deps)
。
5、useMemo使用
把“創(chuàng)建”函數和依賴項數組作為參數傳入?useMemo
,它僅會在某個依賴項改變時才重新計算 memoized 值。這種優(yōu)化有助于避免在每次渲染時都進行高開銷的計算。
6、useRef使用
useRef
?返回一個可變的 ref 對象,其?.current
?屬性被初始化為傳入的參數(initialValue
)。返回的 ref 對象在組件的整個生命周期內持續(xù)存在。
7、useImperativeHandle使用
useImperativeHandle
?可以讓你在使用?ref
?時自定義暴露給父組件的實例值。在大多數情況下,應當避免使用 ref 這樣的命令式代碼。useImperativeHandle
?應當與?forwardRef?一起使用:
8、Hook useMemo useCallback 的區(qū)別
useMemo
?用于優(yōu)化計算開銷大的操作。它會記憶一個值,只有當依賴項改變時,才會重新計算這個值。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
在上面的例子中,computeExpensiveValue
?是一個計算開銷很大的函數,它依賴于變量?a
?和?b
。只有當?a
?或?b
?改變時,computeExpensiveValue
?才會重新計算。
使用場景:
- 計算開銷大的值。
- 需要重用計算結果以避免不必要的計算。
useCallback
?用于優(yōu)化傳遞給子組件的回調函數。
Hook 簡介 – React
React Native Hooks開發(fā)指南