React Hooks 是 React 16.8 版本引入的一个新特性,它允许在不编写额外逻辑的情况下使用状态和其他 React 特性。下面是一些关于 React Hooks 的基础知识和常用例子。
1. 使用状态(useState)
useState 是最常用的 Hook,用于在函数组件中添加状态。
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
2. 使用效果(useEffect)
useEffect 用于执行副作用操作,例如数据获取、订阅或手动更改 DOM。
import React, { useEffect, useState } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('/api/data');
const result = await response.json();
setData(result);
};
fetchData();
}, []);
if (!data) return <div>Loading...</div>;
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
3. 使用上下文(useContext)
useContext 允许你订阅一个 React 上下文(context),并获取其值。
import React, { useContext, useState } from 'react';
import { CountContext } from './CountContext';
function Example() {
const { count, setCount } = useContext(CountContext);
const [localCount, setLocalCount] = useState(0);
return (
<div>
<p>Count from context: {count}</p>
<p>Local count: {localCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setLocalCount(localCount + 1)}>Increment Local</button>
</div>
);
}
更多关于 React Hooks 的内容,可以查看我们的React Hooks 教程。
React Hooks 图标