首页 > web前端 > js教程 > 正文

前端开发 + 数据结构和算法:DSA 如何为您的 React 应用程序提供动力 ⚡

王林
发布: 2024-09-08 22:32:11
原创
878 人浏览过

以前端为中心的面试通常根本不关心 DSA。

对于我们这些记得在学校/大学学习过 DSA 的人来说,所有的例子都感觉纯粹是算法(有充分的理由),但几乎没有任何例子或指导来说明我们每天使用的产品如何利用这个概念。

“我需要这个吗?”
你已经问过很多次这个问题了,不是吗? ?

以下是您今天可以在 React 应用程序中利用的一些数据结构! ?

目录

  1. 简介
  2. 数组:状态管理的首选
  3. 对象和哈希图:标准化数据存储以提高效率
  4. 双向链表:使用上下文导航
  5. 堆栈:具有不可变行为的撤消/重做功能
  6. 队列:管理顺序 API 调用
  7. 树:渲染递归组件
  8. 图表:构建复杂的数据关系和导航
  9. 结论

相关阅读:

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>
  );
}
登录后复制

另一篇可能与您相关的热门帖子:

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!