自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

聊聊React Hook的那些事兒

開發(fā)
通過(guò)使用hook,我們可以解決復(fù)雜組件之間的狀態(tài)問(wèn)題,可以讓組件變得更加輕量化,更加好理解。

什么是react hook

首先,它是在react16.8版本中引入的概念,也就說(shuō)如果你的react版本低于16.8,你是不能使用的,因此在使用它的時(shí)候,一定要注意react的版本。

它將函數(shù)組件的功能升級(jí)了,原來(lái)只能在類組件中使用的state,context等都可以在函數(shù)組件中使用了。

react hook一般是以u(píng)se開頭,比如useState,useEffect,通過(guò)使用這種方式,我們就能夠在函數(shù)組件中使用react的庫(kù)的功能。

react hook 的優(yōu)點(diǎn)

相比于類組件,函數(shù)組件更好理解,類組件中的this關(guān)鍵詞,事件綁定都很讓人頭疼,而使用了react hook之后,這些問(wèn)題就都可以避免了。

相比于類組件,你會(huì)發(fā)現(xiàn)函數(shù)組件的代碼要少得非常多,代碼看起來(lái)很簡(jiǎn)潔,使用起來(lái)也非常的方便,雖然官方?jīng)]有說(shuō)要移除類組件,但是官方更傾向使用函數(shù)組件,如果你是新入門react的話,強(qiáng)烈建議你使用react hook。

使用react hook 的幾個(gè)準(zhǔn)測(cè)

雖然react hook很方便,但是也要遵循幾個(gè)原則來(lái)書寫。

只有在組件的最頂層才可以使用react hook,也就意味著,你不能在循環(huán),條件,嵌套函數(shù)中使用它。方便點(diǎn)記的話就是在return之前使用它。

只在react functions 中使用hook,不要在普通的js函數(shù)中使用它,當(dāng)然你可以在自定義的hooks中使用hook。

React 常用內(nèi)置hook

(1) useState

顧名思義,通過(guò)使用useState,我們可以在函數(shù)組件中創(chuàng)建,更新,操作state.

useState使用方法很簡(jiǎn)單,通過(guò)返回一個(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 (
<div>
Current Cart Count: {count}
<div>
<button onClick={() => setCount(count - 1)}>Add to cart</button>
<button onClick={() => setCount(count + 1)}>Remove from cart</button>
</div>
</div>
);
}

(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 (
<div>
Current {product}'s count: {count}
<div>
<button onClick={() => setCount(count + 1)}>Add to cart</button>
<button onClick={() => setCount(count - 1)}>Remove from cart</button>
Change Product:{" "}
<input type="text" onChange={(e) => setProduct(e.target.value)} />
</div>
</div>
);
}

(3) useContext

它提供了一個(gè)方法可以讓數(shù)據(jù)被整個(gè)應(yīng)用程序的所有組件訪問(wèn)到,相當(dāng)于聲明了一個(gè)全局變量,無(wú)論它被嵌套使用,還是如何使用,其它組件總是能夠訪問(wèn)使用它。

它只有一個(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 (
<div>
{users.map((user) => (
<li>
I am {user.name} and I am a {user.occupation}!
</li>
))}
</div>
);
}

(4) useReducer

這是一個(gè)和useState很類似的hook,唯一的不同就是它允許操作邏輯更復(fù)雜的狀態(tài)更新。

它接收兩個(gè)參數(shù),一個(gè)是更新函數(shù),一個(gè)是初始狀態(tài)。它的返回值有兩個(gè),一個(gè)是被處理的狀態(tài)state,一個(gè)是分派的函數(shù)。

簡(jiǎn)單理解就是useReducer通過(guò)提供的更新函數(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) => (
<div key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.complete}
onChange={() => handleComplete(todo)}
/>
{todo.title}
</label>
</div>
))}
</>
);
}

ReactDOM.render(<Todos />, document.getElementById('root'));

自定義Hooks

通過(guò)組合使用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é)

通過(guò)使用hook,我們可以解決復(fù)雜組件之間的狀態(tài)問(wèn)題,可以讓組件變得更加輕量化,更加好理解。

通過(guò)使用Hook,我們可以在無(wú)需修改組件結(jié)構(gòu)的情況下復(fù)用狀態(tài)邏輯。

因?yàn)榻M件是有狀態(tài)的,因此才有了hook的誕生。

責(zé)任編輯:趙寧寧 來(lái)源: 今日頭條
相關(guān)推薦

2021-06-02 08:33:31

TPCTPC-H系統(tǒng)

2021-05-10 08:58:09

Harbor架構(gòu)Registry 服務(wù)

2022-05-23 08:34:08

微前端微服務(wù)開發(fā)

2021-01-13 11:11:29

TCP連接耗時(shí)網(wǎng)絡(luò)協(xié)議

2022-06-02 08:42:15

Redis數(shù)據(jù)庫(kù)

2013-01-11 16:05:41

求職招聘

2018-04-24 09:05:09

容器存儲(chǔ)接口

2020-05-20 14:25:45

Reactreact.js前端

2020-09-17 13:43:03

等保2.0網(wǎng)絡(luò)安全漏洞

2021-03-02 11:06:17

工業(yè)互聯(lián)網(wǎng)

2019-10-30 14:31:47

Vue 3.0數(shù)組響應(yīng)

2022-03-03 08:01:41

阻塞與非阻塞同步與異步Netty

2022-03-04 08:10:35

NettyIO模型Reactor

2023-04-11 07:34:40

分布式系統(tǒng)算法

2021-03-18 09:01:53

軟件開發(fā)軟件選型

2022-05-26 09:03:39

AOP編程

2017-10-17 18:06:08

2011-02-25 14:35:00

2018-09-26 06:50:19

2022-02-08 17:39:04

MySQL服務(wù)器存儲(chǔ)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)