Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何基于reactjs中的url在reactjs中进行Api调用?_Reactjs_Api_Fetch - Fatal编程技术网

如何基于reactjs中的url在reactjs中进行Api调用?

如何基于reactjs中的url在reactjs中进行Api调用?,reactjs,api,fetch,Reactjs,Api,Fetch,这是我的api url,所以现在我想在重新加载后调用它,我对reactjs是完全陌生的,所以我需要关于如何根据api url使用fetch/axios调用api的基本知识?期待积极的回应 试试这个: import React, { Component } from 'react'; class YourComponent extends Component { state = {} componentDidMount() { Your api call her

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

试试这个:

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调用:

对于获取API调用:


学习React:

为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
};
N.B.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请求进行相应修改。

这是否回答了您的问题?谢谢你的回复。我怀疑,假设“”这个url是否包含作者和描述之类的信息。如果我想为此做一个api调用,你能给我一些关于它的小例子吗?我试过这个“”谢谢你的回答。我怀疑,假设“”这个url是否包含作者和描述之类的信息。如果我想为此做一个api调用,你能给我一些关于它的小例子吗。尝试此操作,但未能获取
...

  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 });
      }
    }
....