Rumah  >  Artikel  >  hujung hadapan web  >  Pembangun Hadapan + Struktur & Algoritma Data: Cara DSA Boleh Menguasakan Apl Reaksi Anda ⚡

Pembangun Hadapan + Struktur & Algoritma Data: Cara DSA Boleh Menguasakan Apl Reaksi Anda ⚡

王林
王林asal
2024-09-08 22:32:11880semak imbas

Frontend focused interviews often don’t care about DSA at all.

And for those of us that remember studying DSA at school/college, all the examples felt purely algorithmic (for good reason), but there were hardly any examples or guidance on how the products we use every day leverage this concept.

“Will I ever need this?”
You’ve asked this a lot, haven’t you? ?

Here are a few data structures that you can leverage in your React app today! ?

Table of Contents

  1. Introduction
  2. Arrays: Your Go-to in State Management
  3. Objects and Hash Maps: Normalized Data Store for Efficiency
  4. Doubly Linked Lists: Navigation with Context
  5. Stacks: Undo/Redo Functionality with Immutable Behavior
  6. Queues: Managing Sequential API Calls
  7. Trees: Rendering Recursive Components
  8. Graphs: Building Complex Data Relationships and Navigation
  9. Conclusion

Related reading:

1. Tatasusunan ?: Pilihan Anda dalam Pengurusan Negeri

Tatasusunan ada di mana-mana dalam React. Jika anda memerlukan bantuan untuk memahami cara .map() atau .filter() berfungsi, anda mungkin melihat siaran ini terlalu cepat! Tetapi jangan risau—sebaik sahaja anda selesa dengan kaedah tatasusunan ini, anda akan melihat betapa pentingnya kaedah tersebut untuk memaparkan senarai, mengurus keadaan komponen dan mengubah data.

2. Objek dan Peta Hash ?️: Stor Data Dinormalisasi untuk Kecekapan

Dalam apl React, apabila anda berurusan dengan koleksi entiti yang besar seperti pengguna atau siaran, menormalkan data anda menjadi objek (peta cincang) boleh menjadikan pembacaan dan pengemaskinian lebih cekap. Daripada bekerja dengan struktur bersarang dalam, anda memetakan entiti mengikut ID mereka.

Contoh: Membaca dari kedai biasa dengan 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>
  );
}

Corak ini membolehkan capaian data yang cekap, terutamanya dengan set data yang besar di mana kemas kini atau pembacaan perlu berlaku dengan cepat tanpa memaparkan semula keseluruhan koleksi.

3. Senarai Berganda Berpaut ?: Navigasi dengan Konteks

Senarai berganda adalah berguna apabila anda memerlukan konteks daripada kedua-dua elemen sebelumnya dan seterusnya—fikirkan untuk menavigasi galeri foto di mana setiap imej memaparkan imej jirannya untuk rujukan. Daripada menggunakan indeks, kami akan menyimpan nod semasa terus dalam keadaan komponen.

Contoh: Senarai berganda untuk navigasi antara elemen dengan konteks

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>
  );
}

Dalam komponen React ini:

  • nod semasa disimpan dalam keadaan dan UI dikemas kini berdasarkan sama ada terdapat nod sebelumnya atau seterusnya.
  • Butang membolehkan pengguna menavigasi senarai ke hadapan dan ke belakang, dan lumpuhkan jika tiada lagi nod untuk dialihkan.
  • Struktur ini meniru navigasi masa nyata dengan konteks daripada elemen sekeliling, yang biasa digunakan dalam komponen UI seperti karusel, galeri media atau senarai main.

4. Tindanan ?: Buat asal/Buat Semula Fungsi dengan Gelagat Tidak Boleh Berubah

Tindanan membolehkan anda mengurus operasi buat asal/buat semula dengan cekap menggunakan logik Masuk Terakhir, Keluar Dahulu (LIFO). Dengan menggunakan operasi tidak berubah (concat, slice), kami boleh memastikan keadaan kekal tidak berubah.

Contoh: Buat asal/Buat semula dengan tolak dan pop yang tidak berubah

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. Baris Gilir ?: Mengurus Panggilan API Berjujukan

Barisan beroperasi dalam cara Masuk Dahulu, Keluar Dahulu (FIFO) dan bagus untuk memastikan tugas seperti panggilan API atau pemberitahuan diproses dalam susunan yang betul.

Contoh: Panggilan API beratur

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. Pokok ?: Memaparkan Komponen Rekursif

Pokok biasanya digunakan dalam React apabila berurusan dengan komponen bersarang seperti benang ulasan, struktur folder atau menu.

Contoh: Memberikan pepohon ulasan secara rekursif

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>
  );
}

Satu lagi siaran popular yang mungkin berkaitan dengan anda:

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!

Atas ialah kandungan terperinci Pembangun Hadapan + Struktur & Algoritma Data: Cara DSA Boleh Menguasakan Apl Reaksi Anda ⚡. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn