簡體   English   中英

ReactJS - axios 攔截器 onSubmit

[英]ReactJS - axios interceptor onSubmit

結構:

ApiService.js
components/
          TrackComponent.jsx

TrackComponent.jsx

我在render()中的 React 中有這個表單,它觸發了一個到達一個端點的事件:

<form onSubmit={ (event) => this.handleEditPlaylist(event) }>
 <div className="field">
   <input
     name="artist"
     className="input is-dark is-large"
     type="text"
   />
  </div>
</form>

手柄 function:

handleEditPlaylist(event) {
    event.preventDefault();
    const formType = this.props.formType
    var headers = {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    const {userId} = this.props
    const data = {
      value: this.state.formData.value,
      spotify_token: this.props.spotifyToken
    };
    const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/handle_edit_playlist/${this.state.artist}/${userId}`;

    axios.post(url, data, {headers: headers})
      .then((res) => {
        console.log(data);
        if(data){this.clearForm();}
      })
      .catch((err) => {
    });

    axios.get(url, { 
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
      }).then((res) => {
          console.log(res.data);
          this.setState({
            seeds: res.data.data[0].seeds,
            artist: res.data.data[0].artist,
          })
      })
  };

這行得通。


組件內的 Api 實例

現在,我有這個axios攔截器,我必須在上面的組件中實例化它,以便處理具有兩個端點的訪問令牌。

import Axios from 'axios';

class ApiService {
  constructor() {
    this.axios = Axios.create();
    this.axios.interceptors.response.use(null, this.authInterceptor.bind(this));

    this.get = this.axios.get.bind(this.axios);
    this.post = this.axios.post.bind(this.axios);
  }

  async authorize() {
    console.log('Async in authorize')
    const { accessToken } = await this.axios.post('/get_token/1', {});
    this.setAccessToken(accessToken);
    return accessToken; // return it to the component that invoked it to store in some state
  }

  async getTrack(userId, spotifyToken, artist) { // <---------------------------
    console.log('getAroma in ApiService', userId, spotifyToken, artist)
    return this.axios.get(
      `${process.env.REACT_APP_WEB_SERVICE_URL}/get-tracks/${artist}/${userId}/${spotifyToken}`
    );
  }

  async updateAccessToken(userId) {
    const { accessToken } = await this.axios.post(`/refresh-token/1`, {});
    this.setAccessToken(accessToken);
  }

  (...)

export const apiService = new ApiService(); // this is a single instance of the service, each import of this file will get it

我希望上面的相同onSubmit事件也觸發攔截器實例化調用。 就其本身而言,我可以這樣做:

import {apiService} from '../ApiService';

async getTrack(event) {
    if (this.props.isAuthenticated) {
      const {userId, spotifyToken} = this.props;
      const {artist} = this.state.artist
      const aromaticTracks = await apiService.getTracks(userId, spotifyToken, artist);
      this.setState({newTracks});
    } else {
      this.setState({newTracks: []});
    }
  }

如果我將這個異步 getTrack 插入到handleEditPlaylist中,就在提交表單之后,如下所示:

(...)

axios.post(url, data, {headers: headers})
      .then((res) => {
        this.getTrack(); // <----------- HERE
        console.log(data);
        if(data){this.clearForm();}
      })
(...)

我在async getTrack console.log('getTrack in ApiService', userId, spotifyToken, artist)中為表單提交的值(藝術家)得到“未定義”,但在下面打印在console.log(data)中提交的值..


如何正確處理這個攔截器onSubmit

您的代碼中的唯一問題是因為您試圖從您已經訪問的 state 中解構一個值

async getTrack(event) {
    if (this.props.isAuthenticated) {
      const {userId, spotifyToken} = this.props;
      const {artist} = this.state; // this needs to be this.state and not this.state.artist
      const aromaticTracks = await apiService.getTracks(userId, spotifyToken, artist);
      this.setState({newTracks});
    } else {
      this.setState({newTracks: []});
    }
  }

destructuring賦值語法是 JavaScript 表達式,它可以將 arrays 中的值或對象的屬性解壓縮到不同的變量中。

閱讀object destructuring的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM