MST

星途 面试题库

面试题:React中useRef Hook在自定义Hook中的深度应用

请设计一个自定义Hook,该Hook使用useRef来跟踪一个值的变化历史,并能提供获取历史记录、重置历史等功能。详细说明你的设计思路,包括如何利用useRef以及处理可能出现的边界情况。
41.7万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 使用useRef: useRef会在组件的整个生命周期内保持其值,并且不会因为组件重新渲染而重置。我们可以利用它来存储值的变化历史。
  2. 跟踪值的变化:每当值发生变化时,将新值添加到useRef所存储的历史数组中。
  3. 获取历史记录功能:提供一个函数来返回useRef中存储的历史数组。
  4. 重置历史功能:提供一个函数将useRef中存储的历史数组重置为空数组。

边界情况处理

  1. 初始值处理:确保在组件首次渲染时,历史记录数组被正确初始化。
  2. 避免重复记录:在添加新值到历史记录时,检查新值是否与历史记录中的最后一个值相同,如果相同则不添加,以避免不必要的记录。

代码实现

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;