聊聊React Hook的那些事儿

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

什么是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,我们可以在函数组件中创建,更新,操作state.

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

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数据请求,更改状态变量等地方。

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

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

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

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

通过组合使用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的诞生。

责任编辑:赵宁宁 来源: 今日头条
相关推荐

2021-06-02 08:33:31

TPCTPC-H系统

2021-05-10 08:58:09

Harbor架构Registry 服务

2022-05-23 08:34:08

微前端微服务开发

2022-06-02 08:42:15

Redis数据库

2021-01-13 11:11:29

TCP连接耗时网络协议

2013-01-11 16:05:41

求职招聘

2018-04-24 09:05:09

容器存储接口

2020-05-20 14:25:45

Reactreact.js前端

2020-09-17 13:43:03

等保2.0网络安全漏洞

2021-03-02 11:06:17

工业互联网

2022-03-04 08:10:35

NettyIO模型Reactor

2019-10-30 14:31:47

Vue 3.0数组响应

2022-03-03 08:01:41

阻塞与非阻塞同步与异步Netty

2023-04-11 07:34:40

分布式系统算法

2021-03-18 09:01:53

软件开发软件选型

2011-02-25 14:35:00

2018-09-26 06:50:19

2022-02-08 17:39:04

MySQL服务器存储

2018-02-02 13:58:59

数据存储

2013-07-09 13:50:05

点赞
收藏

51CTO技术栈公众号