设计思路
- 使用
useRef
: useRef
会在组件的整个生命周期内保持其值,并且不会因为组件重新渲染而重置。我们可以利用它来存储值的变化历史。
- 跟踪值的变化:每当值发生变化时,将新值添加到
useRef
所存储的历史数组中。
- 获取历史记录功能:提供一个函数来返回
useRef
中存储的历史数组。
- 重置历史功能:提供一个函数将
useRef
中存储的历史数组重置为空数组。
边界情况处理
- 初始值处理:确保在组件首次渲染时,历史记录数组被正确初始化。
- 避免重复记录:在添加新值到历史记录时,检查新值是否与历史记录中的最后一个值相同,如果相同则不添加,以避免不必要的记录。
代码实现
import { useRef } from 'react';
const useValueHistory = initialValue => {
const historyRef = useRef([initialValue]);
const addValueToHistory = (newValue) => {
if (historyRef.current[historyRef.current.length - 1]!== newValue) {
historyRef.current.push(newValue);
}
};
const getHistory = () => historyRef.current;
const resetHistory = () => {
historyRef.current = [initialValue];
};
return {
addValueToHistory,
getHistory,
resetHistory
};
};
export default useValueHistory;
使用示例
import React, { useState } from'react';
import useValueHistory from './useValueHistory';
const App = () => {
const [inputValue, setInputValue] = useState('');
const { addValueToHistory, getHistory, resetHistory } = useValueHistory('');
const handleChange = (e) => {
const value = e.target.value;
setInputValue(value);
addValueToHistory(value);
};
const handleReset = () => {
setInputValue('');
resetHistory();
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
<button onClick={handleReset}>Reset</button>
<pre>{JSON.stringify(getHistory(), null, 2)}</pre>
</div>
);
};
export default App;