自定义Hook
2020-12-10 本文已影响0人
Ag_fronted
1、usePrevious绑定state先前的值
import React, { useState, useEffect, useRef } from "react";
import { Button } from "antd";
function usePrevious(value) {
1、const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
2、const current = React.useMemo(
() => ({
current: 0,
}),
[]
);
React.useEffect(() => {
current.current = value;
});
return current.current;
}
function Child({ child, handleChild, ...props }) {
const prevChild = usePrevious(child);
return (
<div>
<Button onClick={handleChild}>{`${child} ${prevChild}`}</Button>
</div>
);
}
export default React.memo(Child);
2、useDebounce延迟加载
import React, { useState } from "react";
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = React.useState(value);
React.useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value]);
return debouncedValue;
};
const App = () => {
const [value, setValue] = React.useState(0);
const lastValue = useDebounce(value, 500);
return (
<div>
<p>
Current: {value} - Debounced: {lastValue}
</p>
<button onClick={() => setValue(value + 1)}>Increment</button>
</div>
);
};
export default App;