如何使用 axios 在 ReactJS 中管理不同的 API 端点

IT技术 reactjs
2021-04-30 09:13:56

在这里,我有我的第一个表单,它从提交按钮提供值 userid 和值 1、2 或 3。 api(代码沙盒中的第 124 行)

  `.post(`https://jsonplaceholder.typicode.com/posts`, payload)` 

然后我有另一个表单,其中三个按钮 nSubmit1、nSubmit2 和 nSubmit3 这些也假设以相同的格式发送值(例如 {userId: "1243", submit: "1"}),

第 168 行在 PostForm.jsx 文件中

  <form>
   <button
            value={submit1}
            onClick={() => this.submitHandler(this.state.submit1)}
          >
            nSubmit1
          </button>
          <button
            value={submit2}
            onClick={() => this.submitHandler(this.state.submit2)}
          >
            nSubmit2
          </button>
          <button
            value={submit3}
            onClick={() => this.submitHandler(this.state.submit3)}
          >
            nSubmit3
          </button>
   </form>

但是对于 diff api,我在哪里以及如何定义第二个 api 并将我的提交值映射到它...userId 假设是两个 api 的公共值

https://codesandbox.io/s/vigorous-ptolemy-p1s4i?file=/src/components/PostForm.js

我还需要以“jsonplaceholder.typicode.com/posts?loadId=${this.userId}&eventName=${this.eventName}”的格式发送有效载荷

2个回答

如果您想以可扩展的方式管理多个端点,我建议您创建一个单独的文件,例如将其命名为 api.js,并在那里创建不同的 axios 实例:

import axios from 'axios'

export const api1 = axios.create({
    baseURL: "https://jsonplaceholder.typicode.com/",
    headers: {
        // You can add some headers here like Token....
        Authorization: "Any Auth Token"
    },
})

export const api2 = axios.create({
    baseURL: "https://myOwnApi.com/",
    headers: {
        // You can add some headers here like Token....
        Authorization: "Any Auth Token"
    },
})


export const api3 = axios.create({
    baseURL: "https://AnotherGreatApi.com/",
    headers: {
        // You can add some headers here like Token....
        Authorization: "Any Auth Token"
    },
})

然后你可以在你的组件中导入它

import React from "react";
import { api1, api2, api3 } from "./api.js";

class PostForm extends React.Component {
  state = {
    userId: "",
    submit1: "1",
    submit2: "2",
    submit3: "3"
  };

  buildPayload = submitName => {
    return { userId: this.state.userId, [`submit`]: submitName };
  };

  changeHandler = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  submitHandler1 = (api, submitName) => {
    const payload = { userId: this.state.userId, [`submit`]: submitName };
    api.post("/post", payload);
  };

  submitHandler2 = (api, eventName) => {
    const payload = { loadId: this.state.userId, eventName };
    api.put("/someRoute", payload);
  };

  submitHandler3 = (api, anotherParam) => {
    const params = { ID: this.state.userId, anotherParam };
    api.get("/someRoute", params);
  };

  render() {
    return (
      <form onSubmit={e => e.preventDefault()}>
        <div>
          <input
            type="text"
            name="userId"
            value={this.state.userId}
            onChange={this.changeHandler}
          />
        </div>
        <button  onClick={() => this.submitHandler1(api1, this.state.submit1)}>Submit1</button>
        <button  onClick={() => this.submitHandler2(api2, "eventName1")} >Submit2</button>
        <button onClick={() => this.submitHandler3(api3, this.state.submit3)} >Submit3</button>
      </form>
    );
  }
}

export default PostForm

您可以修改提交处理程序以接受 API url 作为参数,并将 url 存储在常量中:

import axios from 'axios';
import React from 'react';

const Constants = {
  API1: 'https://jsonplaceholder.typicode.com/',
  API2: 'https://jsonplaceholder.typicode.com/',
  API3: 'https://jsonplaceholder.typicode.com/',
};

class PostForm extends React.Component {
  state = {
    userId: '',
    submit1: '1',
    submit2: '2',
    submit3: '3',
  };

  buildPayload = submitName => {
    return { userId: this.state.userId, [`submit`]: submitName };
  };

  changeHandler = e => {
    this.setState({ [e.target.name]: e.target.value });
  }

  submitHandler = (url, submitName) => {
    const payload = this.buildPayload(submitName);
    axios.post(url, payload)
      .then(response => {
        console.log(response);
      }).catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <form onSubmit={e => e.preventDefault()}>
        <div>
          <input
            type="text"
            name="userId"
            value={this.state.userId}
            onChange={this.changeHandler}
          />
        </div>
        <button onClick={() => this.submitHandler(Constants.API1, this.state.submit1)}>Submit 1</button>
        <button onClick={() => this.submitHandler(Constants.API2, this.state.submit2)}>Submit 2</button>
        <button onClick={() => this.submitHandler(Constants.API3, this.state.submit3)}>Submit 3</button>
      </form>
    );
  }
}

export default PostForm;