Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีโหลดข้อมูลจากเซิร์ฟเวอร์ใน React Native


เพื่อโหลดข้อมูลจากเซิร์ฟเวอร์ สามารถใช้ Fetch API ซึ่งคล้ายกับ XMLHttpRequest หรือ API เครือข่ายอื่นๆ

การใช้งาน Fetch API แบบง่าย

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => response.json())
  .then((responseJson) => console.log(responseJson));

โค้ดด้านบนดึงข้อมูล JSON จาก URL และพิมพ์ลงคอนโซล การเรียก fetch() พื้นฐานรับอาร์กิวเมนต์เดียวคือ path ที่ต้องการดึง และคืนค่า Promise พร้อม response

Fetch API คืนค่า Promise พร้อม HTTP response เพื่อให้ได้ JSON body ต้องใช้เมธอด json()

พารามิเตอร์ที่สองของ fetch API เป็นอ็อบเจ็กต์ที่สามารถระบุ method (GET, POST), headers, และข้อมูลที่ต้องการส่ง

ตัวอย่างที่ทำงานจริง: GET ข้อมูลด้วย Fetch API

สถานะเริ่มต้น

state = {
  data: ''
}

เกี่ยวกับ componentDidMount()

componentDidMount() ถูกเรียกทันทีหลังจากคอมโพเนนต์ถูก mount (หลังจากรองทุกอย่างบนหน้าจอแล้ว)

componentDidMount = () => {
  fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'GET'
  })
  .then((response) => response.json())
  .then((responseJson) => {
    console.log(responseJson);
    this.setState({
      data: responseJson
    });
  })
  .catch((error) => {
    console.error(error);
  });
}

ข้อมูลจาก API

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

เราสนใจแสดงข้อความในฟิลด์ body

อัปเดตสถานะ

this.setState({
  data: responseJson
})

ตอนนี้ this.state.data.body มีข้อมูลจากเซิร์ฟเวอร์ พร้อมแสดงให้ผู้ใช้:

render() {
  return (
    
      
        {this.state.data.body}
      
    
  );
}

โค้ดเต็มรูปแบบ

import React, { Component } from "react";
import { Text, View } from "react-native";

class HttpExample extends Component {
  state = {
    data: ''
  };

  componentDidMount = () => {
    fetch('https://jsonplaceholder.typicode.com/posts/1', {
      method: 'GET'
    })
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson);
      this.setState({
        data: responseJson
      });
    })
    .catch((error) => {
      console.error(error);
    });
  }

  render() {
    return (
      
        
          {this.state.data.body}
        
      
    );
  }
}

const App = () => {
  return (
    
  );
};

export default App;

ผลลัพธ์

วิธีโหลดข้อมูลจากเซิร์ฟเวอร์ใน React Native

แนวทางปฏิบัติที่ดีในปัจจุบัน

  • ใช้ async/await แทน .then() chain เพื่อความอ่านง่าย
  • ใช้ useEffect Hook แทน componentDidMount ใน Functional Component
  • จัดการ error state และ loading state ให้ครบถ้วน
  • พิจารณาใช้ไลบรารีเช่น Axios หรือ React Query สำหรับการจัดการข้อมูลที่ซับซ้อน