State: Bộ Nhớ Của Component

Các component thường cần thay đổi những gì hiển thị trên màn hình do kết quả của một tương tác. Nhập vào form sẽ cập nhật trường input, click “next” trên carousel hình ảnh sẽ thay đổi hình ảnh được hiển thị, click “buy” sẽ đưa sản phẩm vào giỏ hàng. Các component cần “nhớ” những thứ: giá trị input hiện tại, hình ảnh hiện tại, giỏ hàng. Trong React, kiểu bộ nhớ cụ thể của component này được gọi là state.

Bạn sẽ được học

  • Cách thêm một biến state với Hook useState
  • Cặp giá trị nào mà Hook useState trả về
  • Cách thêm nhiều hơn một biến state
  • Tại sao state được gọi là local

Khi một biến thông thường không đủ

Đây là một component render hình ảnh tác phẩm điêu khắc. Click vào nút “Next” sẽ hiển thị tác phẩm tiếp theo bằng cách thay đổi index thành 1, sau đó 2, và tiếp tục. Tuy nhiên, điều này sẽ không hoạt động (bạn có thể thử!):

import { sculptureList } from './data.js';

export default function Gallery() {
  let index = 0;

  function handleClick() {
    index = index + 1;
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}

handleClick là một trình xử lý sự kiện đang cập nhật một biến cục bộ, index. Nhưng hai điều ngăn cản sự thay đổi đó được hiển thị:

  1. Các biến cục bộ không tồn tại giữa các lần render. Khi React render component này lần thứ hai, nó sẽ render lại từ đầu - nó không xem xét bất kỳ thay đổi nào đối với các biến cục bộ.
  2. Thay đổi các biến cục bộ sẽ không kích hoạt render. React không nhận ra rằng nó cần render lại component với dữ liệu mới.

Để cập nhật một component với dữ liệu mới, hai điều cần phải xảy ra:

  1. Giữ lại dữ liệu giữa các lần render.
  2. Kích hoạt React để render component với dữ liệu mới (render lại).

Hook useState cung cấp hai điều đó:

  1. Một biến state để giữ dữ liệu giữa các lần render.
  2. Một hàm setter state để cập nhật biến và kích hoạt React render lại component.

Thêm một biến state

Để thêm một biến state, hãy nhập useState từ React ở đầu file:

import { useState } from 'react';

Sau đó, thay thế dòng này:

let index = 0;

bằng

const [index, setIndex] = useState(0);

index là một biến state và setIndex là hàm setter.

Cú pháp [] ở đây được gọi là array destructuring và nó cho phép bạn đọc giá trị từ một mảng. Mảng được trả về bởi useState luôn có đúng hai mục.

Đây là cách chúng hoạt động cùng nhau trong handleClick:

function handleClick() {
setIndex(index + 1);
}

Bây giờ, khi nhấp vào nút “Next”, tác phẩm điêu khắc hiện tại sẽ được chuyển đổi:

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);

  function handleClick() {
    setIndex(index + 1);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}

Gặp gỡ Hook đầu tiên của bạn

Trong React, useState, cũng như bất kỳ hàm nào khác bắt đầu bằng “use”, được gọi là một Hook.

Hooks là các hàm đặc biệt chỉ có sẵn khi React đang render (mà chúng ta sẽ đi vào chi tiết hơn ở trang tiếp theo). Chúng cho phép bạn “kết nối” với các tính năng khác nhau của React.

State chỉ là một trong những tính năng đó, nhưng bạn sẽ gặp các Hooks khác sau.

Chú Ý

Hooks—các hàm bắt đầu bằng use—chỉ có thể được gọi ở cấp độ trên cùng của các component của bạn hoặc Hooks của riêng bạn. Bạn không thể gọi Hooks bên trong các điều kiện, vòng lặp, hoặc các hàm lồng ghép khác. Hooks là các hàm, nhưng sẽ hữu ích khi nghĩ về chúng như là các khai báo không điều kiện về các nhu cầu của component của bạn. Bạn “sử dụng” các tính năng của React ở đầu component của bạn tương tự như cách bạn “nhập khẩu” các mô-đun ở đầu file của bạn.

Giải phẫu của useState

Khi bạn gọi useState, bạn đang nói với React rằng bạn muốn component này nhớ một cái gì đó:

const [index, setIndex] = useState(0);

Trong trường hợp này, bạn muốn React nhớ index.

Note

Quy ước là đặt tên cho cặp này như const [something, setSomething]. Bạn có thể đặt tên cho nó bất kỳ điều gì bạn thích, nhưng các quy ước làm cho mọi thứ dễ hiểu hơn trên các dự án khác nhau.

Tham số duy nhất của useStategiá trị ban đầu của biến state của bạn. Trong ví dụ này, giá trị ban đầu của index được đặt thành 0 với useState(0).

Mỗi khi component của bạn được render, useState sẽ trả về một mảng chứa hai giá trị:

  1. Biến state (index) với giá trị bạn đã lưu trữ.
  2. Hàm setter state (setIndex) có thể cập nhật biến state và kích hoạt React render lại component.

Đây là cách mà điều đó xảy ra trong thực tế:

const [index, setIndex] = useState(0);
  1. Component của bạn được render lần đầu tiên. Bởi vì bạn đã truyền 0 cho useState như là giá trị ban đầu cho index, nó sẽ trả về [0, setIndex]. React nhớ rằng giá trị state mới nhất là 0.
  2. Bạn cập nhật state. Khi người dùng nhấp vào nút, nó gọi setIndex(index + 1). index0, vì vậy nó là setIndex(1). Điều này nói với React rằng bây giờ hãy nhớ index1 và kích hoạt một lần render khác.
  3. Lần render thứ hai của component của bạn. React vẫn thấy useState(0), nhưng vì React nhớ rằng bạn đã đặt index thành 1, nó trả về [1, setIndex] thay thế.
  4. Và cứ thế tiếp tục!

Cung cấp nhiều biến state cho một component

Bạn có thể có nhiều biến state với nhiều loại khác nhau trong một component. Component này có hai biến state, một số index và một boolean showMore được chuyển đổi khi bạn nhấp vào “Show details”:

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleNextClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <button onClick={handleMoreClick}>
        {showMore ? 'Hide' : 'Show'} details
      </button>
      {showMore && <p>{sculpture.description}</p>}
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
    </>
  );
}

Việc sử dụng nhiều biến state là điều hợp lý nếu chúng không liên quan đến nhau, như indexshowMore trong ví dụ này. Nhưng nếu bạn thấy rằng bạn thường xuyên thay đổi hai biến state cùng lúc, thì bạn có thể dễ dàng hơn nếu kết hợp chúng thành một biến state duy nhất. Ví dụ, nếu bạn có một form với nhiều trường, thì thuận tiện hơn khi sử dụng một biến state duy nhất giữ một object thay vì mỗi trường một biến state riêng. Đọc thêm tại Chọn Cấu Trúc State để biết thêm mẹo.

Tìm hiểu sâu

React làm sao biết state nào để trả về?

Bạn có thể đã nhận ra rằng khi gọi useState, bạn không truyền vào bất kỳ thông tin nào về state nào mà nó đang tham chiếu. Không có “định danh” nào được truyền cho useState, vậy làm sao React biết biến state nào cần trả về? Có phải nó dựa vào phép “ma thuật” nào đó như phân tích cú pháp hàm của bạn không? Câu trả lời là không.

Thay vào đó, để giữ cho cú pháp gọn gàng, Hooks dựa vào thứ tự gọi ổn định ở mỗi lần render của cùng một component. Điều này hoạt động tốt trong thực tế vì nếu bạn tuân theo quy tắc (“chỉ gọi Hooks ở cấp độ trên cùng”), các Hooks sẽ luôn được gọi theo cùng một thứ tự. Thêm vào đó, một linter plugin sẽ phát hiện hầu hết các sai sót.

Về mặt nội bộ, React lưu một mảng các cặp state cho mỗi component. Nó cũng duy trì một biến chỉ số cặp hiện tại, được đặt về 0 trước mỗi lần render. Mỗi khi bạn gọi useState, React trả về cặp state tiếp theo và tăng chỉ số lên. Bạn có thể tìm hiểu thêm về cơ chế này trong React Hooks: Not Magic, Just Arrays.

Ví dụ này không sử dụng React nhưng nó giúp bạn hình dung cách useState hoạt động bên trong:

let componentHooks = [];
let currentHookIndex = 0;

// How useState works inside React (simplified).
function useState(initialState) {
  let pair = componentHooks[currentHookIndex];
  if (pair) {
    // This is not the first render,
    // so the state pair already exists.
    // Return it and prepare for next Hook call.
    currentHookIndex++;
    return pair;
  }

  // This is the first time we're rendering,
  // so create a state pair and store it.
  pair = [initialState, setState];

  function setState(nextState) {
    // When the user requests a state change,
    // put the new value into the pair.
    pair[0] = nextState;
    updateDOM();
  }

  // Store the pair for future renders
  // and prepare for the next Hook call.
  componentHooks[currentHookIndex] = pair;
  currentHookIndex++;
  return pair;
}

function Gallery() {
  // Each useState() call will get the next pair.
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  // This example doesn't use React, so
  // return an output object instead of JSX.
  return {
    onNextClick: handleNextClick,
    onMoreClick: handleMoreClick,
    header: `${sculpture.name} by ${sculpture.artist}`,
    counter: `${index + 1} of ${sculptureList.length}`,
    more: `${showMore ? 'Hide' : 'Show'} details`,
    description: showMore ? sculpture.description : null,
    imageSrc: sculpture.url,
    imageAlt: sculpture.alt
  };
}

function updateDOM() {
  // Reset the current Hook index
  // before rendering the component.
  currentHookIndex = 0;
  let output = Gallery();

  // Update the DOM to match the output.
  // This is the part React does for you.
  nextButton.onclick = output.onNextClick;
  header.textContent = output.header;
  moreButton.onclick = output.onMoreClick;
  moreButton.textContent = output.more;
  image.src = output.imageSrc;
  image.alt = output.imageAlt;
  if (output.description !== null) {
    description.textContent = output.description;
    description.style.display = '';
  } else {
    description.style.display = 'none';
  }
}

let nextButton = document.getElementById('nextButton');
let header = document.getElementById('header');
let moreButton = document.getElementById('moreButton');
let description = document.getElementById('description');
let image = document.getElementById('image');
let sculptureList = [{
  name: 'Homenaje a la Neurocirugía',
  artist: 'Marta Colvin Andrade',
  description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
  url: 'https://i.imgur.com/Mx7dA2Y.jpg',
  alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'  
}, {
  name: 'Floralis Genérica',
  artist: 'Eduardo Catalano',
  description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
  url: 'https://i.imgur.com/ZF6s192m.jpg',
  alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
}, {
  name: 'Eternal Presence',
  artist: 'John Woodrow Wilson',
  description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
  url: 'https://i.imgur.com/aTtVpES.jpg',
  alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
}, {
  name: 'Moai',
  artist: 'Unknown Artist',
  description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
  url: 'https://i.imgur.com/RCwLEoQm.jpg',
  alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
}, {
  name: 'Blue Nana',
  artist: 'Niki de Saint Phalle',
  description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
  url: 'https://i.imgur.com/Sd1AgUOm.jpg',
  alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
}, {
  name: 'Ultimate Form',
  artist: 'Barbara Hepworth',
  description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
  url: 'https://i.imgur.com/2heNQDcm.jpg',
  alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
}, {
  name: 'Cavaliere',
  artist: 'Lamidi Olonade Fakeye',
  description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
  url: 'https://i.imgur.com/wIdGuZwm.png',
  alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
}, {
  name: 'Big Bellies',
  artist: 'Alina Szapocznikow',
  description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
  url: 'https://i.imgur.com/AlHTAdDm.jpg',
  alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
}, {
  name: 'Terracotta Army',
  artist: 'Unknown Artist',
  description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
  url: 'https://i.imgur.com/HMFmH6m.jpg',
  alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
}, {
  name: 'Lunar Landscape',
  artist: 'Louise Nevelson',
  description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
  url: 'https://i.imgur.com/rN7hY6om.jpg',
  alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
}, {
  name: 'Aureole',
  artist: 'Ranjani Shettar',
  description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
  url: 'https://i.imgur.com/okTpbHhm.jpg',
  alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
}, {
  name: 'Hippos',
  artist: 'Taipei Zoo',
  description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
  url: 'https://i.imgur.com/6o5Vuyu.jpg',
  alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];

// Make UI match the initial state.
updateDOM();

Bạn không cần hiểu nó để sử dụng React, nhưng bạn có thể thấy đây là một mô hình tư duy hữu ích.

State được cô lập và riêng tư

State là cục bộ cho từng thể hiện của component trên màn hình. Nói cách khác, nếu bạn render cùng một component hai lần, mỗi bản sao sẽ có state hoàn toàn tách biệt! Việc thay đổi state ở một bản sao sẽ không ảnh hưởng đến bản sao kia.

Ví dụ này, component Gallery từ ví dụ trước được render hai lần mà không thay đổi logic nào. Hãy thử nhấp vào các nút bên trong mỗi gallery. Bạn sẽ thấy state của chúng hoàn toàn độc lập:

import Gallery from './Gallery.js';

export default function Page() {
  return (
    <div className="Page">
      <Gallery />
      <Gallery />
    </div>
  );
}

Điều này làm cho state khác với các biến thông thường mà bạn có thể khai báo ở đầu mô-đun của bạn. State không gắn liền với một cuộc gọi hàm cụ thể hoặc một vị trí trong mã, nhưng nó “cục bộ” cho vị trí cụ thể trên màn hình. Bạn đã render hai component <Gallery />, vì vậy state của chúng được lưu trữ riêng biệt.

Cũng lưu ý rằng component Page không “biết” bất kỳ điều gì về state của Gallery hoặc thậm chí liệu nó có hay không. Khác với props, state hoàn toàn riêng tư với component khai báo nó. Component cha không thể thay đổi nó. Điều này cho phép bạn thêm state vào bất kỳ component nào hoặc loại bỏ nó mà không ảnh hưởng đến phần còn lại của các component.

Điều gì sẽ xảy ra nếu bạn muốn cả hai phòng trưng bày giữ cho các state của chúng đồng bộ? Cách đúng để làm điều đó trong React là loại bỏ state khỏi các component con và thêm nó vào cha gần nhất của chúng. Một vài trang tiếp theo sẽ tập trung vào việc tổ chức state của một component đơn lẻ, nhưng chúng ta sẽ trở lại chủ đề này trong Chia Sẻ State Giữa Các Component.

Tóm tắt

  • Sử dụng một biến state khi một component cần “nhớ” một số thông tin giữa các lần render.
  • Các biến state được khai báo bằng cách gọi Hook useState.
  • Hooks là các hàm đặc biệt bắt đầu bằng use. Chúng cho phép bạn “kết nối” với các tính năng của React như state.
  • Hooks có thể khiến bạn nhớ đến các imports: chúng cần được gọi một cách không điều kiện. Việc gọi Hooks, bao gồm cả useState, chỉ hợp lệ ở cấp độ trên cùng của một component hoặc một Hook khác.
  • Hook useState trả về một cặp giá trị: state hiện tại và hàm để cập nhật nó.
  • Bạn có thể có nhiều hơn một biến state. Ở bên trong, React ghép nối chúng theo thứ tự của chúng.
  • State là riêng tư cho component. Nếu bạn render nó ở hai nơi, mỗi bản sao sẽ nhận được state của riêng nó.

Khi bạn nhấn “Next” ở tượng cuối cùng, code sẽ bị lỗi. Hãy sửa logic để ngăn lỗi này. Bạn có thể thêm logic bổ sung vào hàm xử lý sự kiện hoặc vô hiệu hóa nút khi hành động không thể thực hiện.

Sau khi sửa lỗi đó, thêm nút “Previous” để hiển thị tượng trước. Nó không nên bị lỗi ở tượng đầu tiên.

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleNextClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <button onClick={handleMoreClick}>
        {showMore ? 'Hide' : 'Show'} details
      </button>
      {showMore && <p>{sculpture.description}</p>}
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
    </>
  );
}