ความเข้าใจเกี่ยวกับ State
State คือข้อมูลภายใน Component ที่สามารถเปลี่ยนแปลงได้เมื่อเกิดเหตุการณ์ เช่น การคลิกปุ่มหรือการกรอกข้อมูล State ทำให้ React Native สามารถแสดงผลแบบไดนามิกได้
คุณสมบัติของ State
- ใช้เก็บข้อมูลที่มีการเปลี่ยนแปลงตลอดเวลา
- มีผลต่อการแสดงผล (UI) ของ Component
- ใช้ภายใน Component เท่านั้น (แตกต่างจาก Props ที่ส่งข้อมูลระหว่าง Components)
ตัวอย่าง:
State ช่วยในการเปลี่ยนข้อความเมื่อผู้ใช้กดปุ่ม
การใช้งาน useState HookuseState
เป็น Hook ที่ใช้สำหรับจัดการ State ใน Functional Components
รูปแบบการใช้งาน
1 | const [state, setState] = useState(initialValue); |
state
: ตัวแปรที่เก็บค่าของ StatesetState
: ฟังก์ชันสำหรับอัปเดต StateinitialValue
: ค่าตั้งต้นของ State
ตัวอย่างการใช้งาน useState
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import React, { useState } from 'react' ; import { View, Text, Button, StyleSheet } from 'react-native' ; const CounterApp = () => { const [count, setCount] = useState(0); return ( <View style={styles.container}> <Text style={styles.text}>Count: {count}</Text> <Button title= "Increase" onPress={() => setCount(count + 1)} /> <Button title= "Decrease" onPress={() => setCount(count - 1)} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center' , alignItems: 'center' , }, text: { fontSize: 24, marginBottom: 20, }, }); export default CounterApp; |
คำอธิบายโค้ด:
- ใช้
useState
เพื่อสร้าง State ชื่อcount
และฟังก์ชันsetCount
- เมื่อกดปุ่ม Increase,
setCount
จะเพิ่มค่าcount
ขึ้นทีละ 1 - เมื่อกดปุ่ม Decrease,
setCount
จะลดค่าcount
ลงทีละ 1
ตัวอย่างการอัปเดต State
3.1 การอัปเดต State ด้วยฟังก์ชัน
สามารถอัปเดต State โดยใช้ฟังก์ชันที่รับค่าปัจจุบันของ State ได้
ตัวอย่าง:
1 2 3 4 5 | const [count, setCount] = useState(0); const increase = () => { setCount((prevCount) => prevCount + 1); }; |
ข้อดี:
- ใช้ฟังก์ชันเพื่อหลีกเลี่ยงปัญหาการอ่านค่าของ State ที่ยังไม่ได้อัปเดต
3.2 การจัดการ State ที่เป็น Object หรือ Array
State สามารถเก็บข้อมูลในรูปแบบ Object หรือ Array ได้
ตัวอย่าง
1 2 3 4 5 | const [user, setUser] = useState({ name: 'John' , age: 25 }); const updateAge = () => { setUser((prevUser) => ({ ...prevUser, age: prevUser.age + 1 })); }; |
คำอธิบาย:
- ใช้
...prevUser
เพื่อเก็บค่าเดิมและอัปเดตเฉพาะage
ข้อควรระวังในการจัดการ State:
- State ไม่ควรถูกแก้ไขโดยตรง (immutable)
1 2 3 4 | // ห้ามทำ user.age = 26; // ใช้ setState แทน setUser({ ...user, age: 26 }); |
2. การอัปเดต State อาจเป็น asynchronous
- ควรใช้ฟังก์ชันเพื่ออ้างถึงค่าปัจจุบันของ State