useState,useEffect,useCallback,useMemo,useRef,useContext的用法
时间: 2023-07-20 17:26:07 浏览: 153
Context的使用
1. useState:用于在函数式组件中添加状态(state)。useState返回一个数组,包含当前状态和一个更新状态的函数。例如:
```javascript
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
2. useEffect:用于在函数式组件中添加副作用(side effect),例如订阅事件、修改 DOM 等。useEffect 接受两个参数,第一个参数是一个函数,用于执行副作用操作,第二个参数是一个数组,用于指定副作用的依赖项。例如:
```javascript
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
3. useCallback:用于缓存函数,避免不必要的重新渲染。useCallback 接受两个参数,第一个参数是需要缓存的函数,第二个参数是一个依赖数组。例如:
```javascript
import React, { useState, useCallback } from 'react';
function Example() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
```
4. useMemo:用于缓存计算结果,避免重复计算。useMemo 接受两个参数,第一个参数是需要缓存的函数,第二个参数是一个依赖数组。例如:
```javascript
import React, { useState, useMemo } from 'react';
function Example() {
const [count, setCount] = useState(0);
const result = useMemo(() => {
return count * 2;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<p>The result is {result}</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
5. useRef:用于在函数式组件中创建一个可变的引用(reference)。useRef 返回一个包含引用值的对象。例如:
```javascript
import React, { useState, useRef } from 'react';
function Example() {
const [count, setCount] = useState(0);
const timerRef = useRef(null);
const handleClick = () => {
timerRef.current = setInterval(() => {
setCount(count => count + 1);
}, 1000);
};
const handleStopClick = () => {
clearInterval(timerRef.current);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Start
</button>
<button onClick={handleStopClick}>
Stop
</button>
</div>
);
}
```
6. useContext:用于在函数式组件中访问上下文(context)。useContext 接受一个上下文对象(由 React.createContext 创建),并返回当前上下文的值。例如:
```javascript
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function Example() {
const theme = useContext(ThemeContext);
return (
<div>
<p>Current theme is: {theme}</p>
</div>
);
}
```
阅读全文