การดึงข้อมูลจาก store ในคอมโพเนนต์ของ Redux

ในบทเรียนนี้ เราจะแสดงข้อมูลจาก store ใน React component

เปิดแอปพลิเคชันสินค้าของเรา เข้าไปที่ โฟลเดอร์ parts/products และสร้างไฟล์ ProductsList.jsx ในนั้น ขั้นแรกนำเข้า hook useSelector ซึ่งเราจะใช้ เพื่อดึงข้อมูลจาก store:

parts/products/ProductsList.jsximport { useSelector } from 'react-redux'

ทีนี้ลองดึงสินค้าจาก store กัน เราจะไม่สร้างฟังก์ชัน selector แยกต่างหาก แต่จะเขียนโค้ดของมันลงในพารามิเตอร์ของ useSelector โดยตรง:

parts/products/ProductsList.jsxexport const ProductsList = () => {
  const products = useSelector((state) => state.products)
}

จากนั้นเราจะแสดงสินค้าด้วยวิธีมาตรฐาน ในตัวฟังก์ชัน ProductsList หลังจาก บรรทัดที่ดึงสินค้า โดยใช้ map:

parts/products/ProductsList.jsxconst dispProducts = products.map((product) => (
  <div key={product.id}>
    <h3>{product.name}</h3>
    <p>{product.desc.substring(0, 100)}</p>
    <p>Price: {product.price}</p>
    <p>Amount: {product.amount}</p>
  </div>
))

และด้านล่างจะแสดง dispProducts ใน markup ต่อไปนี้:

parts/products/ProductsList.jsxreturn (
  <div>
    <h2>Products</h2>
    {dispProducts}
  </div>
)

ตอนนี้เหลือเพียงการแสดงรายการ สินค้าของเราบนหน้าหลัก เปิด ไฟล์ root.jsx และแก้ไขหัวเรื่อง:

app/root.jsx<h2>This is my first Redux app!</h2>

เป็นดังนี้:

app/root.jsx<h2>My Products App</h2>

จากนั้นนำเข้า component ProductsList เข้าไปในไฟล์:

app/root.jsximport { ProductsList } from '../parts/products/ProductsList'

และแทรกมันเข้าไปใน div ที่มี id main-page ทันทีหลังจากแท็กปิด hr:

app/root.jsx<ProductsList />

เริ่มต้นแอปพลิเคชันของเรา รายการ สินค้าทั้งสองชิ้นของเราแสดงผลสำเร็จบนหน้า หลัก

Задание 1

เปิดแอปพลิเคชันนักเรียนของคุณ สร้างไฟล์ StudentsList.jsx ในโฟลเดอร์ students

Задание 2

ดึงข้อมูลนักเรียนจาก store โดยใช้ hook useSelector ตามที่อธิบายในบทเรียน แสดงฟิลด์ข้อมูลทั้งหมดเกี่ยวกับ นักเรียนจาก state โดยใช้ map

Задание 3

นำเข้า component ที่ได้ StudentsList ไปยัง root.jsx และ แสดงผลบนหน้าหลัก ตรวจสอบให้แน่ใจว่า ข้อมูลทั้งหมดเกี่ยวกับนักเรียน แสดงบนหน้าจอ