如何在react js中将其余的api调用保留在不同的文件中

Liq*_*ath 8 reactjs axios

我是 React js 的新手,并且一直在构建一些工作得非常好的东西。但到目前为止,要进行的 api 调用是在各自的组件内定义的。因此,如果要对 IP 或端点进行任何更改,我需要在每个地方进行更改。如何将所有 api 调用分离到一个文件中,并在相应的组件文件中对结果执行操作。

下面是一个例子:

import axios from "axios";

function get_all_user(){
axios({
      method: "get",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      url: "http://127.0.0.1:8000/app/users/",
    })
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      })
      
}

function get_single_user(userid){

axios({
      method: "get",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      url: "http://127.0.0.1:8000/app/users/"+userid,
    })
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      })
      
}
Run Code Online (Sandbox Code Playgroud)

在每个组件中我都需要进行 api 调用。所有这些 api 调用都需要位于一处。任何帮助表示赞赏。

Sow*_*wam 7

您可以将整个代码移动到另一个组件中,并export在函数定义之前添加单词,例如:

export function get_all_user(){
  // rest of code
}
Run Code Online (Sandbox Code Playgroud)

然后你只需将其导入到你的组件中

import { get_all_user } from './path/to/file/'
Run Code Online (Sandbox Code Playgroud)

因此您可以通过以下方式在多个文件中使用它们:

get_all_user()
Run Code Online (Sandbox Code Playgroud)

是一个示例,它是text.js您导出函数的文件,在index.js文件中您只需使用它