【问题标题】:How to make an Api call in reactjs based on url in reactjs?如何根据reactjs中的url在reactjs中进行Api调用?
【发布时间】:2020-09-19 08:20:46
【问题描述】:

这是我的 api url,所以现在我想在重新渲染发生后调用它,我对 reactjs 完全陌生,所以我需要有关如何根据 api url 使用 fetch/axios 调用 api 的基本知识?期待积极的回应。

http://newsapi.org/v2/everything?q=tech&apiKey=008c2c412a2b403698bc29a732374513&pageSize=10&page=1

【问题讨论】:

标签: reactjs api fetch


【解决方案1】:

试试这个:

import React, { Component } from 'react';

class YourComponent extends Component {
    state = {}

    componentDidMount() {
        Your api call here...
    }

    render() {
        return (
             Your Codes Here...
        )
    }
}

export default YourComponent;

Axios API 调用:https://youtu.be/4uzEUATtNHQ

对于 Fetch API 调用:
https://youtu.be/cuEtnrL9-H0

学习 React:https://www.youtube.com/playlist?list=PL4cUxeGkcC9ij8CfkAY2RAGb-tmkNwQHG

【讨论】:

【解决方案2】:

为您的 HTTP 客户端服务创建一个可重用的组件。

// httpService.js 
import axios from "axios"
axios.interceptors.response.use(null, error => {
    const expectedError =
        error.response &&
        error.response.status >= 400 &&
        error.response.status < 500;
    if (!expectedError) {
        console.log("Logging the error", error);
        alert("An unexpected error occurred");

    }
    return Promise.reject(error);
});
export default {
    get: axios.get,
    post: axios.post,
    put: axios.put,
    delete: axios.delete
};

以下是对用户信息的注册发布请求示例

// authService.js 

import http from "../services/httpService"
import { apiUrl } from "../../config.json"
const apiEndPoint = apiUrl + "";
export function register(user) {
  return http.post(apiEndPoint, {
    firstname: user.firstname,
    secondname: user.secondname,
    email: user.email,
    phone: user.phone,
    password: user.password,
  });
}

注意Config.json 文件包含您的 API URL

下面是一个注册表单组件示例,它有一个 doSubmit 方法,用于在成功注册后调用服务器并导航到登录页面。

...

  doSubmit = async () => {
    // Call Server
    try {
      await userService.register(this.state.data);
      this.props.history.push("/Login"); // Programmatic Routing
    } catch (ex) {
      if (ex.response && ex.response.status === 400) {
        const errors = { ...this.state.errors };
        errors.username = ex.response.data;
        this.setState({ errors });
      }
    }
....

此示例仅用于说明目的,可以根据您的 API 请求进行相应修改。

【讨论】:

猜你喜欢
  • 2018-03-10
  • 2018-06-19
  • 2019-03-31
  • 2018-06-24
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
相关资源
最近更新 更多