React中常见Hooks总结
React Hooks是React 16.8及更高版本引入的特性,它们可以让你在函数组件中使用state以及其他的React特性而无需写class。
以下是一些常用的React Hooks以及它们的简单描述和用法示例:
- useState
import React, { useState } from 'react';
function Example() {
// 声明一个叫 "count" 的 state 变量
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
- useEffect
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// 类似于类组件中的componentDidMount和componentDidUpdate
useEffect(() => {
// 更新document的title
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
- useContext
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Button() {
const theme = useContext(ThemeContext);
return (
<button style={{ backgroundColor: theme.background }}>
I am styled by theme context!
</button>
);
}
- useReducer
import React, { useReducer } from 'react';
function Example() {
// 类似于useState,但用于管理复杂的state
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement
</button>
</div>
);
}
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();
}
}
- useCallback
import React, { useCallback } from 'react';
function Example() {
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
return <SomeComponent onSomething={memoizedCallback} />;
}
- useMemo
import React, { useMemo } from 'react';
function Example() {
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
return <div>{memoizedValue}</div>;
}
- useRef
评论已关闭