React手撕组件和Hooks总结

计数器

typescript 复制代码
const Counter=({initialState)=>{
	const [count,setCount]=useState(initialState);
	const handleIncrement=()=>{
		setCount(preCount=>preCount+1);
	}
	return (
		<div>
			<div>当前计数:{count}</div>
			<button onClick={handleIncrement}</button>
		</div>
		)
}

setCount(count + 1)setCount(preCount => preCount + 1)

状态更新的直接与函数式差异

setCount(count + 1)直接基于当前count值进行更新。若在短时间内连续调用多次,可能因闭包问题导致更新未按预期累积。例如:

javascript 复制代码
// 连续调用三次,可能因闭包中的count未及时更新而只生效一次
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);

函数式更新的可靠性

setCount(preCount => preCount + 1)通过函数参数接收最新的状态值,确保每次更新基于前一个状态。即使快速连续调用,也能正确累积:

javascript 复制代码
// 连续调用三次,最终count会增加3
setCount(prev => prev + 1);
setCount(prev => prev + 1);
setCount(prev => prev + 1);

异步场景下的表现差异

在异步操作(如setTimeoutuseEffect)中,直接更新可能因闭包捕获旧值而出错。函数式更新始终能获取最新状态:

javascript 复制代码
useEffect(() => {
  setTimeout(() => {
    setCount(count + 1); // 可能使用过时的count
    setCount(prev => prev + 1); // 始终正确
  }, 1000);
}, []);

批量更新的处理

React的批量更新机制下,直接更新多次会被合并,函数式更新则按队列顺序执行:

javascript 复制代码
// 直接更新:合并为一次+1
setCount(count + 1);
setCount(count + 1);

// 函数式更新:按顺序执行两次+1
setCount(prev => prev + 1);
setCount(prev => prev + 1);

依赖项的注意事项

当状态更新依赖前一个状态时,函数式更新可避免手动添加依赖项到useEffectuseCallback的依赖数组,减少不必要的重渲染风险。

总结场景选择

  • 直接更新 :适用于不依赖前状态的简单赋值或已知无并发风险的场景。
  • 函数式更新 :必须用于依赖前状态的逻辑、异步环境或可能存在批量更新的场景

底层知识点useState

异步,React批量更新

在 setTimeout、原生事件 或 异步操作 中,setState 会立即触发更新:但在 React 18 中,所有更新(包括 Promise、setTimeout 等)默认启用自动批量更新,需使用 flushSync 强制同步:

useState简单手撕实现

React 内部通过 ​​链表结构​​ 管理 Hooks 状态,依赖调用顺序追踪状态。以下是简化版实现(闭包):

javascript 复制代码
let stateQueue=[];
let setter=[];
let index=0;

function createSetter(index){
	return (newValue)=>{
		stateQueue[index]=typeof newValue==="function"?
				newValue(stateQueue[index]):newValue;
		//重新渲染
		index=0;
		render();
	}
}

function render(){
	ReactDom.render(<App/>,document.getElementById("root"))

function useState(initialState){
	if(stateQueue[index]===undefined){
		stateQueue[index]=initialState;
		setter[index]=createSetter(index);
	}
	const currentState=stateQueue[index];
	const currentSetter=setter[index];
	index++;//下一个Hook
	return [currentState,currentSetter]
}

受控输入框组件

  • 如何添加输入验证功能?->验证函数,返回错误条件 err
  • 如果想在用户停止输入 500ms 后才更新内容,应该如何实现?->防抖 debounceTimer
javascript 复制代码
const ControllerInput=()=>{
	const [inputValue,setInputValue]=useState("");
	const [debounceTimer,setDebounceTimer]=useState(null);
	const [err,setErr]=useState("");
	const validateInput=()=>{
		const regExp=/^[a-zA-Z0-9]*$/;
		if(!regExp.test(value))return "输入数据只能为数字和字母"
		return "";
	}
	const handleChange=(event)=>{
	    const value=event.target.value;
		if(debounceTimer)clearTimeout(debounceTimer);
		//验证数据
		const validationErr=validateInput(value);
		setErr(validationErr);
		const timer=setTimeout(()=>{
			setInputValue();
		},500);
		setDebounceTimer(timer);
	}
	
	return (
		<div>
			<input 
				type="text"
				value={inputValue}
				onChange={handleChange}
			/>
		</div>
	)
}
export default ControllerInput;

模态框组件

javascript 复制代码
const Modal=({visible,onClose,children})=>{
	useEffect(()=>{
		if(!visible)return;
		//Esc关闭&滚动锁定
		const handleEsc=(e)=>e.key==="Escape"&&onClose?.();
		document.body.style.overflow="hidden";
		window.addEventListener('keydown',handleEsc);
		return ()=>{
			window.removeEventListenr(ketdown',handleEsc);
			document.body.style.overflow="";
		}
	},[visible,onClose]);
	//Portal挂载到body
	return visible?ReactDOM.createPortal(
	     <div
	     	style={{
	     		position:"fixed",
	     		top:0,left:0,right:0,bottom:0,
	     		display:"flex",
	     		justifyContent:"center",alignItems:"center"
	     		}}
	     >
		     <div className="modal-content"
		     	  style={{
		     	  	  backgroundColor:"white"
		     >
		     	{children}	
		     </div>
	     </div>,
	     documnet.body
	     ):null;
	
}


//父组件
import React, { useState } from 'react';
import Modal from './Modal';

function App() {
  const [isModalVisible, setIsModalVisible] = useState(false);

  // 控制模态框显示
  const showModal = () => {
    setIsModalVisible(true);
  };

  // 关闭模态框
  const hideModal = () => {
    setIsModalVisible(false);
  };

  return (
    <div>
      <button onClick={showModal}>显示模态框</button>
      
      {/* 渲染模态框,传入 isVisible 和 onClose props */}
      <Modal isVisible={isModalVisible} onClose={hideModal}>
        <h2>欢迎来到模态框</h2>
        <p>这是模态框的内容!</p>
      </Modal>
    </div>
  );
}

export default App;
  • 1.​​Portal挂载​​解决层级问题

  • 2.​​双动画CSS​​实现流畅体验

  • 3.​​滚动锁定​​需记录原始值

  • 4.​​事件隔离​​精准控制关闭条件

ja