输入reactjs时取消axios get请求

时间:2017-03-20 06:05:54

标签: reactjs axios

我正在创建一个自动完成功能,所以基本上每当我在搜索框中输入时,它都会取消之前的http get请求。我检查了jQuery ui autocomplete以及他们做了什么。在axios中是否可能,如果是,我该如何实现它。到目前为止,我的代码是http get request:

export function autocompleteSearchTest(value){
    return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`,{
        params: {
            q: value
        }
    })
    .then(response => {
        return response.data.response;
    })
    .catch(error => {
        const result = error.response;
        return Promise.reject(result);
    });
}

点击我在搜索框中输入的屏幕截图:

enter image description here

你可以看到它没有取消之前的http get请求。

5 个答案:

答案 0 :(得分:12)

自axios v0.15起,您可以取消请求:

  

您还可以通过传递执行程序函数来创建取消令牌   CancelToken构造函数:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

有关详细信息,请查看Cancellation。根据你的代码:

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

export function autocompleteSearchTest(value) {
    if (cancel != undefined) {
        cancel();
    }
    return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`, {
        cancelToken: new CancelToken(function executor(c) {
            // An executor function receives a cancel function as a parameter
            cancel = c;
        }),
        params: {
            q: value
        }
    })
        .then(response => {
            return response.data.response;
        })
        .catch(error => {
            const result = error.response;
            return Promise.reject(result);
        });
}

var CancelToken = axios.CancelToken;
var cancel;

export class AutoComplete extends React.Component {

    constructor() {
        super()
        this.state = {
            search: ''
        };
        this.handleSearchChange = this.handleSearchChange.bind(this);
    }

    handleSearchChange(event) {
        const target = event.target;
        const value = target.value;
        this.setState({
            search: value
        });
        autocompleteSearchTest(value)
    }

    render() {
        return (
            <div className="App-intro Dialog-section">
                <h2>AutoComplete</h2>
                <div className="form-control">
                    <label htmlFor="password">Lookup :</label>
                    <input name="search" type="text" value={this.state.search}
                           onChange={this.handleSearchChange}
                           id="password" ref="password" placeholder="Enter line"/>
                </div>
            </div>
        )
    }
}

export default AutoComplete;

就在这里 enter image description here

答案 1 :(得分:1)

使用faxios

// building..
let req = faxios()
  .baseURL("http://jsonplaceholder.typicode.com")
  .url("posts", 1, "comments")

// fetching..
req // => 
  .FETCH // => Promise
  .then(res => {})
  .catch(err => {});

// canceling...
req.cancel();

答案 2 :(得分:1)

您可以创建一个小的辅助包装器,并在需要取消先前请求的任何地方使用它:

// ../services.js

function createApi(baseURL) {
  const axiosInst = axios.create({
    baseURL,
  });

  axiosInst.defaults.headers.common['Content-Type'] = 'application/json';
  
  return (type = 'get') => {
    let call = null;
    return (url, data, config) => {
      if (call) {
        call.cancel('Only one request allowed!');
      }
      call = axios.CancelToken.source();
      const extConf = {
        cancelToken: call.token,
        ...config,
      };
      switch (type) {
        case 'request':
          return api[type](extConf);

        case 'get':
        case 'delete':
        case 'head':
          return api[type](url, extConf);

        default:
          return api[type](url, data, extConf);
      }
    };
  };
}

export const baseApi = createApi('http://localhost:5000/api/')

然后在这样的任何地方使用它:

import baseApi from '../servises.js';

const fetchItemsService = baseApi('post');

//...
componentDidMount() {
  fetchItemsService('/items').then(() => {});
}
//...

答案 3 :(得分:0)

你想使用像RxJS这样的东西,然后你可以在用户搜索之前延迟输入,然后才能发出请求。

答案 4 :(得分:0)

使用:react,axios和redux-axios-middleware

用户操作:

import axios from 'axios';
import * as type from 'constants/user';

const CancelToken = axios.CancelToken;
let cancel;

export const addUser = (data) => {
  if (cancel !== undefined) cancel();

  return ({
    types: [type.ADD_USER_REQUEST, type.ADD_USER_SUCCESS, type.ADD_USER_FAILURE],
    payload: {
      request: {
        url: '/api/user',
        cancelToken: new CancelToken(c => cancel = c),
        method: 'POST',
        data,
      },
    },
  });
};