react如何調(diào)用接口獲取數(shù)據(jù)

小億
224
2024-01-23 13:07:19

在 React 中,可以通過使用 fetch 或者 axios 等庫(kù)來(lái)調(diào)用接口獲取數(shù)據(jù)。

使用 fetch 的示例代碼如下:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // 處理獲取到的數(shù)據(jù)
    console.log(data);
  })
  .catch(error => {
    // 處理錯(cuò)誤
    console.error(error);
  });

使用 axios 的示例代碼如下:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    // 處理獲取到的數(shù)據(jù)
    console.log(response.data);
  })
  .catch(error => {
    // 處理錯(cuò)誤
    console.error(error);
  });

在實(shí)際開發(fā)中,通常會(huì)將數(shù)據(jù)獲取的邏輯放在 React 組件的生命周期方法(如 componentDidMount)中,以便在組件掛載后立即獲取數(shù)據(jù)。獲取到的數(shù)據(jù)可以存儲(chǔ)在組件的狀態(tài)中,然后在 render 方法中使用。

例如:

import React, { Component } from 'react';
import axios from 'axios';

class MyComponent extends Component {
  state = {
    data: null,
    error: null,
  };

  componentDidMount() {
    axios.get('https://api.example.com/data')
      .then(response => {
        // 更新組件狀態(tài)
        this.setState({ data: response.data });
      })
      .catch(error => {
        // 更新組件狀態(tài)
        this.setState({ error: error.message });
      });
  }

  render() {
    const { data, error } = this.state;

    if (error) {
      return <div>Error: {error}</div>;
    }

    if (!data) {
      return <div>Loading...</div>;
    }

    return (
      <div>
        {/* 使用獲取到的數(shù)據(jù)渲染組件 */}
      </div>
    );
  }
}

export default MyComponent;

在上述代碼中,組件在掛載后會(huì)調(diào)用 componentDidMount 方法,該方法中使用 axios 發(fā)起請(qǐng)求并將獲取到的數(shù)據(jù)存儲(chǔ)在組件的狀態(tài)中。在 render 方法中根據(jù)組件的狀態(tài)來(lái)渲染不同的內(nèi)容。

0