您好,登录后才能下订单哦!
React Hooks 是 React 16.8 版本引入的一个新特性,它允许你在不编写类(class)的情况下使用 state 和其他 React 特性。以下是一些常用的 React Hooks API 及其使用技巧:
useState
是一个让函数组件可以使用 state 的 Hook。
使用技巧:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>Click me</button>
</div>
);
}
useEffect
是一个让函数组件可以使用副作用(如数据获取、订阅、手动修改 DOM 等)的 Hook。
使用技巧:
useEffect
的第二个参数是一个依赖数组,只有当数组中的值发生变化时,副作用才会重新执行。[]
),副作用只会在组件挂载和卸载时执行。import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useContext
是一个让函数组件可以使用 React context 的 Hook。
使用技巧:
useContext
,无需使用 Consumer
组件。import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>I am styled by theme context!</button>;
}
useReducer
是一个让函数组件可以使用更复杂 state 逻辑的 Hook。
使用技巧:
useReducer
接受一个 reducer 函数和一个初始 state,返回当前的 state 和一个 dispatch 函数。import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
useCallback
是一个返回记忆化回调函数的 Hook。
使用技巧:
useCallback
返回的函数才会重新创建。import React, { useCallback, useState } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, [setCount]);
return <ChildComponent onIncrement={increment} />;
}
useMemo
是一个返回记忆化值的 Hook。
使用技巧:
useMemo
返回的值才会重新计算。import React, { useMemo, useState } from 'react';
function ExpensiveComponent({ list }) {
const [filter, setFilter] = useState('');
const filteredList = useMemo(() => {
return list.filter(item => item.includes(filter));
}, [list, filter]);
return (
<div>
<input value={filter} onChange={e => setFilter(e.target.value)} />
{filteredList.map(item => <p key={item}>{item}</p>)}
</div>
);
}
useRef
是一个返回可变的 ref 对象的 Hook。
使用技巧:
useRef
返回的对象在组件的整个生命周期内保持不变。import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
自定义 Hooks 是一个让你能够提取组件逻辑到可重用函数的 Hook。
使用技巧:
use
开头,以便与 React 提供的内置 Hooks 区分开来。import React, { useState, useEffect } from 'react';
function useCustomHook() {
const [data, setData] = useState(null);
useEffect(() => {
fetchData().then(fetchedData => setData(fetchedData));
}, []);
return data;
}
function MyComponent() {
const data = useCustomHook();
return <div>{data}</div>;
}
通过合理使用这些 Hooks,你可以编写出更加简洁、高效和易于维护的 React 组件。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。