react hooks 彻底改变了我们在 react 中编写功能组件的方式,使我们无需编写类即可使用状态和其他 react 功能。本指南将向您介绍基本的钩子、自定义钩子和高级钩子模式,以管理复杂的状态并优化性能。
react hooks 是让您从功能组件“挂钩”react 状态和生命周期功能的函数。 hooks 是在 react 16.8 中引入的,它们提供了一种更直接的方式在功能组件中使用状态和其他 react 功能。
usestate 是一个钩子,允许您向功能组件添加状态。
示例:
import react, { usestate } from 'react';
const counter = () => {
const [count, setcount] = usestate(0);
return (
<div>
<p>you clicked {count} times</p>
<button onclick="{()"> setcount(count + 1)}>click me</button>
</div>
);
};
export default counter;
在此示例中,usestate 将 count 状态变量初始化为 0。setcount 函数在单击按钮时更新状态。
useeffect 是一个钩子,可让您在功能组件中执行副作用,例如获取数据、直接与 dom 交互以及设置订阅。它结合了类组件中多个生命周期方法的功能(componentdidmount、componentdidupdate 和 componentwillunmount)。
import react, { usestate, useeffect } from 'react';
const datafetcher = () => {
const [data, setdata] = usestate(null);
useeffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setdata(data));
}, []);
return (
<div>
{data ? <pre class="brush:php;toolbar:false">{json.stringify(data, null, 2)}
'loading...'}