新聞中心
什么是react hook
它將函數(shù)組件的功能升級(jí)了,原來只能在類組件中使用的state,context等都可以在函數(shù)組件中使用了。

順慶網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián)公司,順慶網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為順慶上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的順慶做網(wǎng)站的公司定做!
react hook一般是以u(píng)se開頭,比如useState,useEffect,通過使用這種方式,我們就能夠在函數(shù)組件中使用react的庫的功能。
react hook 的優(yōu)點(diǎn)
相比于類組件,函數(shù)組件更好理解,類組件中的this關(guān)鍵詞,事件綁定都很讓人頭疼,而使用了react hook之后,這些問題就都可以避免了。
相比于類組件,你會(huì)發(fā)現(xiàn)函數(shù)組件的代碼要少得非常多,代碼看起來很簡潔,使用起來也非常的方便,雖然官方?jīng)]有說要移除類組件,但是官方更傾向使用函數(shù)組件,如果你是新入門react的話,強(qiáng)烈建議你使用react hook。
使用react hook 的幾個(gè)準(zhǔn)測
雖然react hook很方便,但是也要遵循幾個(gè)原則來書寫。
只有在組件的最頂層才可以使用react hook,也就意味著,你不能在循環(huán),條件,嵌套函數(shù)中使用它。方便點(diǎn)記的話就是在return之前使用它。
只在react functions 中使用hook,不要在普通的js函數(shù)中使用它,當(dāng)然你可以在自定義的hooks中使用hook。
React 常用內(nèi)置hook
(1) useState
顧名思義,通過使用useState,我們可以在函數(shù)組件中創(chuàng)建,更新,操作state.
useState使用方法很簡單,通過返回一個(gè)state變量和一個(gè)更新state變量的函數(shù)。
import { useState } from "react";
function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
Current Cart Count: {count}
);
}(2) useEffect
在react的生命周期中,我們有componentDidMount,componentDidUpdate,componentWillUnmount等方法,而useEffect就是整合了這些方法。
useEffect主要用在Api數(shù)據(jù)請(qǐng)求,更改狀態(tài)變量等地方。
useEffect有兩個(gè)參數(shù),一個(gè)是要運(yùn)行的函數(shù),一個(gè)是包含組件的props,context,state等變量的數(shù)組。如果沒有后面依賴的數(shù)組,就表示每次渲染都要執(zhí)行第一個(gè)參數(shù)的函數(shù)。
import { useState, useEffect } from "react";
function Counter() {
// Declare state variables
const [count, setCount] = useState(0);
const [product, setProduct] = useState("Eggs");
useEffect(() => {
console.log(`${product} will rule the world!`);
}, [product]);
return (
Current {product}'s count: {count}
Change Product:{" "}
setProduct(e.target.value)} />
);
}(3) useContext
它提供了一個(gè)方法可以讓數(shù)據(jù)被整個(gè)應(yīng)用程序的所有組件訪問到,相當(dāng)于聲明了一個(gè)全局變量,無論它被嵌套使用,還是如何使用,其它組件總是能夠訪問使用它。
它只有一個(gè)參數(shù),就是React.createContext函數(shù)的返回值。
import React from "react";
// some mock context values
const users = [
{
name: "Harry Potter",
occupation: "Wizard",
},
{
name: "Kent Clark",
occupation: "Super hero",
},
];
export const UserContext = React.createContext(users);
import React, { useContext } from "react";
import { UserContext } from "./App";
export function UserProfile() {
const users = useContext(UserContext);
return (
{users.map((user) => (
I am {user.name} and I am a {user.occupation}!
))}
);
}(4) useReducer
這是一個(gè)和useState很類似的hook,唯一的不同就是它允許操作邏輯更復(fù)雜的狀態(tài)更新。
它接收兩個(gè)參數(shù),一個(gè)是更新函數(shù),一個(gè)是初始狀態(tài)。它的返回值有兩個(gè),一個(gè)是被處理的狀態(tài)state,一個(gè)是分派的函數(shù)。
簡單理解就是useReducer通過提供的更新函數(shù)對(duì)state進(jìn)行相應(yīng)的更新處理。
import { useReducer } from "react";
import ReactDOM from "react-dom";
const initialTodos = [
{
id: 1,
title: "Todo 1",
complete: false,
},
{
id: 2,
title: "Todo 2",
complete: false,
},
];
const reducer = (state, action) => {
switch (action.type) {
case "COMPLETE":
return state.map((todo) => {
if (todo.id === action.id) {
return { ...todo, complete: !todo.complete };
} else {
return todo;
}
});
default:
return state;
}
};
function Todos() {
const [todos, dispatch] = useReducer(reducer, initialTodos);
const handleComplete = (todo) => {
dispatch({ type: "COMPLETE", id: todo.id });
};
return (
<>
{todos.map((todo) => (
))}
>
);
}
ReactDOM.render( , document.getElementById('root'));自定義Hooks
通過組合使用react內(nèi)置的hook,我們可以生成我們自己的hook。
//useFetch.js
import { useState, useEffect } from "react";
export function useFetch(url) {
//values
const [data, setData] = useState(null);
const [error, setError] = useState("");
useEffect(() => {
fetch(url)
.then(res => {
if (!res.ok) {
throw Error("something wrong, ?ould not connect to resource");
}
setData(res.json());
})
.then(() => {
setError("");
})
.catch( error => {
console.warn(`sorry an error occurred, due to ${error.message} `);
setData(null);
setError(error.message);
});
}, [url]);
return [data, error];
}
總結(jié)
通過使用hook,我們可以解決復(fù)雜組件之間的狀態(tài)問題,可以讓組件變得更加輕量化,更加好理解。
通過使用Hook,我們可以在無需修改組件結(jié)構(gòu)的情況下復(fù)用狀態(tài)邏輯。
因?yàn)榻M件是有狀態(tài)的,因此才有了hook的誕生。
名稱欄目:聊聊ReactHook的那些事兒
文章來源:http://m.fisionsoft.com.cn/article/cccdjhe.html


咨詢
建站咨詢
