React前端面试题手写代码全攻略 从基础到高阶常见题型解析与代码实现技巧分享

引言
在现代前端开发面试中,React作为最流行的前端框架之一,其手写代码题往往是考察候选人基础功底和实际问题解决能力的关键环节。手写代码不仅测试你对React核心概念的理解,还考察你的代码组织能力、性能优化意识以及对最佳实践的掌握程度。本文将系统性地梳理React面试中的手写代码题型,从基础到高阶,提供详细的解析和代码实现技巧,帮助你全面备战React面试。
一、基础概念与核心API手写题
1.1 手写useState和useEffect
题目
:请手写一个简化的useState和useEffect实现,理解React Hooks的工作原理。
解析
:这是考察对React Hooks底层原理理解的经典题目。面试官希望看到你对闭包、状态管理和副作用处理的理解。
代码实现
:
// 模拟React的全局状态管理
let currentComponent = null;
let hookIndex = 0;

function useState(initialState) {
// 获取当前组件的hook状态
const component = currentComponent;
const index = hookIndex;

// 初始化状态
if (!component.hooks[index]) {
component.hooks[index] = {
state: initialState,
deps: null
};
}

const hook = component.hooks[index];

// 更新状态的函数
const setState = (newValue) => {
if (typeof newValue === ‘function’) {
hook.state = newValue(hook.state);
} else {
hook.state = newValue;
}
// 触发重新渲染
component.render();
};

hookIndex++;
return [hook.state, setState];
}

function useEffect(callback, deps) {
const component = currentComponent;
const index = hookIndex;

const hook = component.hooks[index] || {
deps: undefined,
cleanup: null
};

// 检查依赖是否变化
const depsChanged = !deps ||
!hook.deps ||
deps.some((dep, i) => dep !== hook.deps[i]);

if (depsChanged) {
// 执行清理函数(如果存在)
if (hook.cleanup) {
hook.cleanup();
}
// 执行副作用
hook.cleanup = callback();
hook.deps = deps;
}

component.hooks[index] = hook;
hookIndex++;
}

// 模拟组件
class Component {
constructor(props) {
this.props = props;
this.hooks = [];
this.state = {};
}

render() {
// 重置hook索引
hookIndex = 0;
currentComponent = this;

// 调用用户定义的render方法
const element = this._render();

currentComponent = null;
return element;
}

_render() {
// 这里应该由子类实现
return null;
}
}

// 使用示例
class MyComponent extends Component {
_render() {
const [count, setCount] = useState(0);
const [name, setName] = useState(‘React’);

useEffect(() => {
console.log(`Count changed to: ${count}`);
return () => console.log(‘Cleanup’);
}, [count]);

return {
type: ‘div’,
props: {
children: [
`Count: ${count}`,
`Name: ${name}`,
{
type: ‘button’,
props: {
onClick: () => setCount(c => c + 1),
children: ‘Increment’
}
}
]
}
};
}
}

// 测试
const myComponent = new MyComponent();
console.log(myComponent.render()); // 初始渲染
myComponent.render(); // 重新渲染
技巧总结
:
使用闭包保存状态
维护hook索引确保顺序一致性
依赖数组比较实现useEffect的优化
理解函数式更新(setState with function)的重要性
1.2 手写高阶组件(HOC)
题目
:请手写一个高阶组件,为组件添加loading状态管理。
解析
:HOC是React中重要的模式,考察对组件复用和组合的理解。
代码实现
:
import React from ‘react’;

// 高阶组件:添加loading状态
function withLoading(WrappedComponent) {
// 返回新的组件类
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
data: null,
error: null
};
}

// 模拟数据加载
loadData = async (url) => {
this.setState({ isLoading: true, error: null });

try {
const response = await fetch(url);
const data = await response.json();
this.setState({
isLoading: false,
data,
error: null
});
return data;
} catch (error) {
this.setState({
isLoading: false,
data: null,
error: error.message
});
throw error;
}
}

render() {
const { isLoading, data, error } = this.state;

// 注入额外的props
const injectedProps = {
loading: isLoading,
loadData: this.loadData,
apiData: data,
apiError: error
};

return (

{isLoading &&

加载中…

}
{error &&

错误: {error}

}

);
}
};
}

// 使用示例
const UserProfile = ({ name, email, loading, loadData, apiData }) => {
return (

{name}

{email}


{apiData && (

API数据:

{JSON.stringify(apiData, null, 2)}

)}

);
};

// 应用高阶组件
const UserProfileWithLoading = withLoading(UserProfile);

// 在应用中使用
function App() {
return ;
}
技巧总结
:
HOC应该保持纯函数,不修改原组件
正确传递props,避免props丢失
考虑displayName等静态属性的传递
处理多个HOC组合时的顺序问题
1.3 手写受控组件与非受控组件
题目
:分别实现受控组件和非受控组件的表单处理。
解析
:这是React表单处理的核心概念,必须熟练掌握。
代码实现
:
// 受控组件示例
class ControlledForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: ”,
email: ”,
password: ”,
errors: {}
};
}

handleChange = (e) => {
const { name, value } = e.target;
this.setState({ [name]: value });

// 实时验证
if (name === ’email’) {
this.validateEmail(value);
}
}

validateEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
this.setState(prev => ({
errors: { …prev.errors, email: ‘无效的邮箱格式’ }
}));
} else {
this.setState(prev => ({
errors: { …prev.errors, email: ” }
}));
}
}

handleSubmit = (e) => {
e.preventDefault();
const { username, email, password } = this.state;

// 提交前的验证
if (!username || !email || !password) {
alert(‘请填写所有字段’);
return;
}

console.log(‘提交数据:’, { username, email, password });
// 发送请求…
}

render() {
const { username, email, password, errors } = this.state;

return (




{errors.email && {errors.email}}


);
}
}

// 非受控组件示例
class UncontrolledForm extends React.Component {
constructor(props) {
super(props);
this.usernameRef = React.createRef();
this.emailRef = React.createRef();
this.passwordRef = React.createRef();
}

handleSubmit = (e) => {
e.preventDefault();

// 在提交时获取DOM节点的值
const username = this.usernameRef.current.value;
const email = this.emailRef.current.value;
const password = this.passwordRef.current.value;

if (!username || !email || !password) {
alert(‘请填写所有字段’);
return;
}

console.log(‘提交数据:’, { username, email, password });
// 发送请求…

// 可以重置表单
e.target.reset();
}

render() {
return (





);
}
}

// 函数式组件中的非受控组件(使用useRef)
function UncontrolledFunctionalForm() {
const usernameRef = React.useRef(null);
const emailRef = React.useRef(null);
const passwordRef = React.useRef(null);

const handleSubmit = (e) => {
e.preventDefault();

const username = usernameRef.current.value;
const email = emailRef.current.value;
const password = passwordRef.current.value;

console.log(‘提交数据:’, { username, email, password });
};

return (





);
}
技巧总结
:
受控组件:状态驱动,适合需要实时验证和复杂交互的场景
非受控组件:DOM驱动,适合简单表单或集成第三方库
合理选择使用场景,避免过度复杂化
二、React Hooks手写题
2.1 手写自定义Hook:useFetch
题目
:请手写一个useFetch Hook,处理异步数据获取。
解析
:考察对自定义Hook的理解,以及错误处理、加载状态管理等实际问题。
代码实现
:
import { useState, useEffect, useCallback, useRef } from ‘react’;

// 自定义Hook:useFetch
function useFetch(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

// 使用useRef来追踪组件是否挂载,避免内存泄漏
const isMounted = useRef(true);

// 使用useCallback优化,避免每次渲染都创建新函数
const fetchData = useCallback(async () => {
if (!url) return;

setLoading(true);
setError(null);

try {
const response = await fetch(url, options);

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const result = await response.json();

if (isMounted.current) {
setData(result);
}
} catch (err) {
if (isMounted.current) {
setError(err.message);
}
} finally {
if (isMounted.current) {
setLoading(false);
}
}
}, [url, options]);

useEffect(() => {
isMounted.current = true;
fetchData();

// 清理函数
return () => {
isMounted.current = false;
};
}, [fetchData]);

// 提供手动重新加载的功能
const refetch = useCallback(() => {
fetchData();
}, [fetchData]);

return { data, loading, error, refetch };
}

// 使用示例:用户列表组件
function UserList() {
const { data: users, loading, error, refetch } = useFetch(‘https://jsonplaceholder.typicode.com/users’);

if (loading) return

加载中…

;
if (error) return

错误: {error}

;

return (

用户列表

    {users && users.map(user => (

  • {user.name} – {user.email}
  • ))}

);
}

// 高级版本:支持取消请求
function useFetchWithCancel(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

const controllerRef = useRef(null);

const fetchData = useCallback(async () => {
// 取消之前的请求
if (controllerRef.current) {
controllerRef.current.abort();
}

// 创建新的AbortController
controllerRef.current = new AbortController();

setLoading(true);
setError(null);

try {
const response = await fetch(url, {
…options,
signal: controllerRef.current.signal
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const result = await response.json();
setData(result);
} catch (err) {
if (err.name !== ‘AbortError’) {
setError(err.message);
}
} finally {
setLoading(false);
}
}, [url, options]);

useEffect(() => {
fetchData();

return () => {
if (controllerRef.current) {
controllerRef.current.abort();
}
};
}, [fetchData]);

const refetch = useCallback(() => {
fetchData();
}, [fetchData]);

return { data, loading, error, refetch };
}
技巧总结
:
使用useRef追踪组件状态,避免内存泄漏
使用useCallback优化性能
提供手动重新加载功能
考虑请求取消机制
处理竞态条件(race conditions)
2.2 手写自定义Hook:useDebounce
题目
:请手写一个useDebounce Hook,用于防抖处理。
解析
:考察对闭包、定时器管理和Hook生命周期的理解。
代码实现
:
import { useState, useEffect, useRef } from ‘react’;

// 基础版本:防抖值
function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
// 设置定时器
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

// 清理定时器
return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}

// 高级版本:防抖函数
function useDebouncedCallback(callback, delay = 500) {
const timeoutRef = useRef(null);
const callbackRef = useRef(callback);

// 更新回调引用
useEffect(() => {
callbackRef.current = callback;
}, [callback]);

const debouncedFunction = (…args) => {
// 清理之前的定时器
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}

// 设置新的定时器
timeoutRef.current = setTimeout(() => {
callbackRef.current(…args);
}, delay);
};

// 清理函数
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);

return debouncedFunction;
}

// 使用示例:搜索框
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState(”);
const [results, setResults] = useState([]);

// 防抖的搜索值
const debouncedSearchTerm = useDebounce(searchTerm, 500);

useEffect(() => {
if (debouncedSearchTerm) {
// 模拟API搜索
console.log(‘执行搜索:’, debouncedSearchTerm);
// 实际项目中这里调用API
setResults([`结果1: ${debouncedSearchTerm}`, `结果2: ${debouncedSearchTerm}`]);
} else {
setResults([]);
}
}, [debouncedSearchTerm]);

return (

setSearchTerm(e.target.value)}
placeholder=”搜索…”
/>

{results.map((result, index) => (

{result}

))}

);
}

// 使用示例:窗口大小调整监听
function ResizeListener() {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});

const handleResize = useDebouncedCallback(() => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight
});
}, 250);

useEffect(() => {
window.addEventListener(‘resize’, handleResize);
return () => window.removeEventListener(‘resize’, handleResize);
}, [handleResize]);

return (

窗口大小: {windowSize.width} x {windowSize.height}

);
}
技巧总结
:
使用useRef保存定时器ID,避免闭包陷阱
正确的清理逻辑防止内存泄漏
区分防抖值和防抖函数的使用场景
考虑延迟时间的可配置性
2.3 手写自定义Hook:useLocalStorage
题目
:请手写一个useLocalStorage Hook,实现状态与localStorage的同步。
解析
:考察对浏览器API、状态管理和Hook副作用的综合运用。
代码实现
:
import { useState, useEffect, useCallback } from ‘react’;

// 自定义Hook:useLocalStorage
function useLocalStorage(key, initialValue) {
// 使用函数式初始化,避免重复计算
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error);
return initialValue;
}
});

// 封装setValue,处理localStorage同步
const setValue = useCallback((value) => {
try {
// 允许函数式更新
const valueToStore = value instanceof Function ? value(storedValue) : value;

setStoredValue(valueToStore);

// 保存到localStorage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error);
}
}, [key, storedValue]);

// 监听localStorage变化(跨标签页同步)
useEffect(() => {
const handleStorageChange = (e) => {
if (e.key === key) {
try {
const newValue = e.newValue ? JSON.parse(e.newValue) : initialValue;
setStoredValue(newValue);
} catch (error) {
console.warn(`Error parsing localStorage value for key “${key}”:`, error);
}
}
};

window.addEventListener(‘storage’, handleStorageChange);

return () => {
window.removeEventListener(‘storage’, handleStorageChange);
};
}, [key, initialValue]);

return [storedValue, setValue];
}

// 使用示例:主题切换
function ThemeSwitcher() {
const [theme, setTheme] = useLocalStorage(‘theme’, ‘light’);

useEffect(() => {
document.body.className = `theme-${theme}`;
}, [theme]);

return (

当前主题: {theme}



);
}

// 使用示例:表单持久化
function PersistentForm() {
const [formData, setFormData] = useLocalStorage(‘form_data’, {
name: ”,
email: ”,
message: ”
});

const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
…prev,
[name]: value
}));
};

const handleSubmit = (e) => {
e.preventDefault();
console.log(‘提交数据:’, formData);
// 提交后清空
setFormData({ name: ”, email: ”, message: ” });
};

return (