您现在的位置是:亿华云 > 系统运维

聊聊React Hook的那些事儿

亿华云2025-10-03 20:24:29【系统运维】8人已围观

简介什么是react hook首先,它是在react16.8版本中引入的概念,也就说如果你的react版本低于16.8,你是不能使用的,因此在使用它的时候,一定要注意react的版本。它将函数组件的功能升

什么是聊聊react hook

首先,它是那事在react16.8版本中引入的概念,也就说如果你的聊聊react版本低于16.8,你是那事不能使用的,因此在使用它的聊聊时候,一定要注意react的那事版本。

它将函数组件的聊聊功能升级了,原来只能在类组件中使用的那事state,context等都可以在函数组件中使用了。

react hook一般是聊聊以use开头,比如useState,那事useEffect,通过使用这种方式,聊聊我们就能够在函数组件中使用react的那事库的功能。

react hook 的聊聊优点

相比于类组件,函数组件更好理解,那事类组件中的聊聊this关键词,事件绑定都很让人头疼,而使用了react hook之后,这些问题就都可以避免了。

相比于类组件,站群服务器你会发现函数组件的代码要少得非常多,代码看起来很简洁,使用起来也非常的方便,虽然官方没有说要移除类组件,但是官方更倾向使用函数组件,如果你是新入门react的话,强烈建议你使用react hook。

使用react hook 的几个准测

虽然react hook很方便,但是也要遵循几个原则来书写。

只有在组件的最顶层才可以使用react hook,也就意味着,你不能在循环,条件,嵌套函数中使用它。方便点记的话就是在return之前使用它。

只在react functions 中使用hook,不要在普通的js函数中使用它,当然你可以在自定义的hooks中使用hook。

React 常用内置hook

(1) useState

顾名思义,通过使用useState,我们可以在函数组件中创建,云南idc服务商更新,操作state.

useState使用方法很简单,通过返回一个state变量和一个更新state变量的函数。

import { useState } from "react";

function Counter() {

// Declare a new state variable, which well call "count"

const [count, setCount] = useState(0);

return (

Current Cart Count: { count}

);

}

(2) useEffect

在react的生命周期中,我们有componentDidMount,componentDidUpdate,componentWillUnmount等方法,而useEffect就是整合了这些方法。

useEffect主要用在Api数据请求,更改状态变量等地方。

useEffect有两个参数,一个是要运行的函数,一个是包含组件的props,context,state等变量的数组。如果没有后面依赖的数组,就表示每次渲染都要执行第一个参数的函数。

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

它提供了一个方法可以让数据被整个应用程序的所有组件访问到,相当于声明了一个全局变量,无论它被嵌套使用,还是如何使用,其它组件总是能够访问使用它。

它只有一个参数,就是云服务器React.createContext函数的返回值。

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

这是一个和useState很类似的hook,唯一的不同就是它允许操作逻辑更复杂的状态更新。

它接收两个参数,一个是更新函数,一个是初始状态。它的返回值有两个,一个是被处理的状态state,一个是分派的函数。

简单理解就是useReducer通过提供的更新函数对state进行相应的更新处理。

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) => (

type="checkbox"

checked={ todo.complete}

onChange={ () => handleComplete(todo)}

/>

{ todo.title}

))}

);

}

ReactDOM.render(<Todos />, document.getElementById(root));自定义Hooks

通过组合使用react内置的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];

}总结

通过使用hook,我们可以解决复杂组件之间的状态问题,可以让组件变得更加轻量化,更加好理解。

通过使用Hook,我们可以在无需修改组件结构的情况下复用状态逻辑。

因为组件是有状态的,因此才有了hook的诞生。

很赞哦!(6942)