前端开发 + 数据结构和算法:DSA 如何为您的 React 应用程序提供动力 ⚡
以前端为中心的面试通常根本不关心 DSA。
对于我们这些记得在学校/大学学习过 DSA 的人来说,所有的例子都感觉纯粹是算法(有充分的理由),但几乎没有任何例子或指导来说明我们每天使用的产品如何利用这个概念。
“我需要这个吗?”
你已经问过很多次这个问题了,不是吗? ?
以下是您今天可以在 React 应用程序中利用的一些数据结构! ?
目录
- 简介
- 数组:状态管理的首选
- 对象和哈希图:标准化数据存储以提高效率
- 双向链表:使用上下文导航
- 堆栈:具有不可变行为的撤消/重做功能
- 队列:管理顺序 API 调用
- 树:渲染递归组件
- 图表:构建复杂的数据关系和导航
- 结论
相关阅读:


从 SDE1 到 SDE2,甚至更远! ?实际需要什么。
Jayant Bhawal 中间件 ・ 6 月 10 日
1. 数组?:状态管理的首选
数组在 React 中无处不在。如果您需要帮助了解 .map() 或 .filter() 的工作原理,您可能会太早看到这篇文章了!但不用担心,一旦您熟悉了这些数组方法,您就会发现它们对于渲染列表、管理组件状态和转换数据是多么重要。
2. 对象和哈希图 ️:标准化数据存储以提高效率
在 React 应用程序中,当您处理大量实体(例如用户或帖子)时,将数据规范化为对象(哈希图)可以使读取和更新更加高效。您无需使用深层嵌套结构,而是通过 ID 映射实体。
示例:从带有ID的规范化存储中读取
const postsById = { 1: { id: 1, title: 'First Post', content: 'Content of first post' }, 2: { id: 2, title: 'Second Post', content: 'Content of second post' } }; const postIds = [1, 2]; function PostList() { return ( <div> {postIds.map(id => ( <Post key={id} post={postsById[id]} /> ))} </div> ); } function Post({ post }) { return ( <div> <h2>{post.title}</h2> <p>{post.content}</p> </div> ); }
这种模式可以实现高效的数据访问,特别是对于需要快速更新或读取而无需重新渲染整个集合的大型数据集。
3. 双向链表?:带上下文的导航
当您需要上一个和下一个元素的上下文时,双向链表非常有用 - 想象一下导航照片库,其中每个图像都显示其相邻图像以供参考。我们不使用索引,而是直接将当前节点存储在组件状态中。
示例:用于在具有上下文的元素之间导航的双向链表
class Node { constructor(value) { this.value = value; this.next = null; this.prev = null; } } class DoublyLinkedList { constructor() { this.head = null; this.tail = null; } add(value) { const newNode = new Node(value); if (!this.head) { this.head = newNode; this.tail = newNode; } else { this.tail.next = newNode; newNode.prev = this.tail; this.tail = newNode; } } } const imageList = new DoublyLinkedList(); imageList.add({ id: 1, src: 'image1.jpg', alt: 'First Image' }); imageList.add({ id: 2, src: 'image2.jpg', alt: 'Second Image' }); imageList.add({ id: 3, src: 'image3.jpg', alt: 'Third Image' }); function Gallery() { const [currentNode, setCurrentNode] = useState(imageList.head); return ( <div> {currentNode.prev && ( <img src={currentNode.prev.value.src} alt={currentNode.prev.value.alt} className="prev-image" /> )} <img src={currentNode.value.src} alt={currentNode.value.alt} className="main-image" /> {currentNode.next && ( <img src={currentNode.next.value.src} alt={currentNode.next.value.alt} className="next-image" /> )} <div> <button onClick={() => setCurrentNode(currentNode.prev)} disabled={!currentNode.prev}> Previous </button> <button onClick={() => setCurrentNode(currentNode.next)} disabled={!currentNode.next}> Next </button> </div> </div> ); }
在此 React 组件中:
- 当前节点存储在状态中,并且UI根据是否有上一个或下一个节点进行更新。
- 这些按钮使用户能够向前和向后导航列表,如果没有更多节点可移动到,则禁用。
- 此结构使用周围元素的上下文来模拟实时导航,通常用于轮播、媒体库或播放列表等 UI 组件中。
4. Stacks ?:具有不可变行为的撤消/重做功能
堆栈允许您使用后进先出 (LIFO) 逻辑有效地管理撤消/重做操作。通过使用不可变操作(concat、slice),我们可以确保状态保持不变。
示例:使用不可变的推送和弹出来撤消/重做
const [undoStack, setUndoStack] = useState([]); const [redoStack, setRedoStack] = useState([]); const [formState, setFormState] = useState({ name: '', email: '' }); const updateForm = (newState) => { setUndoStack(prev => prev.concat([formState])); // Immutable push setRedoStack([]); // Clear redo stack setFormState(newState); }; const undo = () => { if (undoStack.length > 0) { const lastState = undoStack.at(-1); setUndoStack(prev => prev.slice(0, -1)); // Immutable pop setRedoStack(prev => prev.concat([formState])); // Move current state to redo setFormState(lastState); } }; const redo = () => { if (redoStack.length > 0) { const lastRedo = redoStack.at(-1); setRedoStack(prev => prev.slice(0, -1)); // Immutable pop setUndoStack(prev => prev.concat([formState])); // Push current state to undo setFormState(lastRedo); } };
5. 队列?:管理顺序 API 调用
队列以先进先出 (FIFO) 方式运行,非常适合确保 API 调用或通知等任务按正确的顺序处理。
示例:排队 API 调用
const [apiQueue, setApiQueue] = useState([]); const enqueueApiCall = (apiCall) => { setApiQueue(prevQueue => prevQueue.concat([apiCall])); // Immutable push }; const processQueue = () => { if (apiQueue.length > 0) { const [nextCall, ...restQueue] = apiQueue; nextCall().finally(() => setApiQueue(restQueue)); // Immutable pop } };
6. 树?:渲染递归组件
React 中通常在处理嵌套组件时使用树,例如 评论线程、文件夹结构或菜单。
示例:递归渲染评论树
const commentTree = { id: 1, text: "First comment", children: [ { id: 2, text: "Reply to first comment", children: [] }, { id: 3, text: "Another reply", children: [{ id: 4, text: "Nested reply" }] } ] }; function Comment({ comment }) { return ( <div> <p>{comment.text}</p> {comment.children?.map(child => ( <div style={{ paddingLeft: '20px' }} key={child.id}> <Comment comment={child} /> </div> ))} </div> ); }
另一篇可能与您相关的热门帖子:


少写,永不修复:高度可靠代码的艺术
中间件 Dhruv Agarwal ・ 6 月 17 日
7. Graphs ?: Building Complex Data Relationships and Navigation
Example 1: Routing between multiple views
You can represent routes between pages as a graph, ensuring flexible navigation paths in an SPA.
const routesGraph = { home: ['about', 'contact'], about: ['home', 'team'], contact: ['home'], }; function navigate(currentRoute, targetRoute) { if (routesGraph[currentRoute].includes(targetRoute)) { console.log(`Navigating from ${currentRoute} to ${targetRoute}`); } else { console.log(`Invalid route from ${currentRoute} to ${targetRoute}`); } }
Example 2: User relationship modeling
Graphs are perfect for modeling social connections or any kind of relationship where multiple entities are interconnected.
const usersGraph = { user1: ['user2', 'user3'], user2: ['user1', 'user4'], user3: ['user1'], user4: ['user2'] }; function findConnections(userId) { return usersGraph[userId] || []; } console.log(findConnections('user1')); // Outputs: ['user2', 'user3']
Note: We use graphs to show reviewer dependencies in Middleware.
TL;DR — Those School Lessons Pay Off
Those DSA classes might have felt abstract back in the day, but data structures are powering the world around you in React.
Objects, stacks, queues, linked lists, trees, and graphs are more than just theory — they’re the backbone of the clean, efficient, and scalable apps you build every day.
So the next time you manage state in a queue or handle complex UI logic, remember: you’ve been training for this since school. ?
Let me know which data structures you’ve been using the most!
以上是前端开发 + 数据结构和算法:DSA 如何为您的 React 应用程序提供动力 ⚡的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

实现视差滚动和元素动画效果的探讨本文将探讨如何实现类似资生堂官网(https://www.shiseido.co.jp/sb/wonderland/)中�...

学习JavaScript不难,但有挑战。1)理解基础概念如变量、数据类型、函数等。2)掌握异步编程,通过事件循环实现。3)使用DOM操作和Promise处理异步请求。4)避免常见错误,使用调试技巧。5)优化性能,遵循最佳实践。

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

如何在JavaScript中将具有相同ID的数组元素合并到一个对象中?在处理数据时,我们常常会遇到需要将具有相同ID�...

探索前端中类似VSCode的面板拖拽调整功能的实现在前端开发中,如何实现类似于VSCode...
