iT邦幫忙

2024 iThome 鐵人賽

DAY 21
0
佛心分享-SideProject30

用React Native打造找餐店APP系列 第 21

[Day 21] 功能開發-安裝axios請求API

  • 分享至 

  • xImage
  •  

昨天我們介紹了如何規劃使用列表元件 FlatList 來渲染資料。現在,接下來的步驟就是準備資料,並將這些資料填入列表元件中。

開發流程:

  • 安裝 Axios:用來發送 HTTP 請求,獲取資料。
  • 撰寫函式:負責請求 API 並處理回應。
  • 將資料填入列表元件:將 API 回應的資料傳遞給 FlatList 元件,讓其渲染。

為資料設定一個狀態,初始為空陣列

const [menu, setAllMenu] = useState([]);

定義函式來處理 API 請求

const handleClickGetMenu = () => {
  axios
    .get(
      'https://json-server-vercel-w33n-git-main-raychen1996.vercel.app/Menus'
    )
    .then(response => {
      console.log(response.data);
      setAllMenu(response.data); // 將獲取的資料更新到狀態
      setIsLoading(false); // 停止載入狀態
      setRefreshing(false); // 停止刷新
    })
    .catch(error => {
      console.error('Error fetching menu:', error);
      setIsLoading(false); // 停止載入狀態
    });
};
  1. axios.get()
    定義: axios.get() 是一個發送 GET 請求的方法,通常用來從伺服器獲取資料。
    用法:
axios.get('URL', [config])
  • URL: 要發送請求的目標網址。
  • config (可選): 用於配置請求的選項,如 headers、params 等。
  1. then()
    定義: then() 是一個方法,用來處理 Promise 成功解決後的結果。在 Axios 中,當請求成功時會執行 then() 內的callback函式。

用法:

axios.get('URL')
  .then(response => {
    // 成功取得響應後的處理邏輯
  });

response: 回調函式的參數,包含伺服器回傳的數據和其他相關資訊(如狀態碼、headers 等)。

  1. catch()
    定義: catch() 是一個方法,用來處理 Promise 拒絕後的錯誤。在 Axios 中,當請求發生錯誤時會執行 catch() 內的回調函式。
axios.get('URL')
  .catch(error => {
    // 處理錯誤的邏輯
  });

error: 回調函式的參數,包含錯誤訊息及其他相關資訊。

使用 FlatList 渲染資料

<FlatList
  data={menu} // 將資料設置到 data 屬性
  renderItem={renderItem}
  keyExtractor={item => item.id.toString()}
  refreshControl={
    <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
  }
/>

明天將分享將每一筆餐點加入購物車~


上一篇
[Day 20] 功能開發-列表顯示元件
下一篇
[Day 22] 功能開發-將Menu加入購物車(資料篇)
系列文
用React Native打造找餐店APP25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言