React Live搜索功能有效,但不会取消“网络”选项卡中的先前请求

时间:2019-10-19 07:56:35

标签: javascript reactjs axios livesearch

我正在关注有关“ alligator.io”的教程。 链接为:https://alligator.io/react/live-search-with-axios/

代码:: App.js

import React, { Component } from 'react';
import { avoidUnnecessarySearch } from './utils';
import './App.css';

class App extends Component {
  state = {
    movies: null,
    loading: false,
    value: ''
  };

  search = async val => {
    this.setState({ loading: true });
    const res = await avoidUnnecessarySearch(
      `https://api.themoviedb.org/3/search/movie?query=${val}&api_key=aac2c5b048fc2fae15675475f98c6ef7`
    );
    const movies = await res ? res.results:'';
    console.log(movies);

    // this.setState({ movies, loading: false });
  };

  onChangeHandler = async e => {
    this.search(e.target.value);
    this.setState({ value: e.target.value });
  };


  render() {
    return (
      <div>
          <input
            value={this.state.value}
            onChange={e => this.onChangeHandler(e)}
            placeholder="Type something to search"
            />

      </div>
    )
  }
}
export default App;


Utils.js

import axios from 'axios';

const makeRequestCreator = () => {
  let token;
  return async (query) => {
   // Check if we made a request
   if(token){
     // Cancel the previous request before making a new request
     token.cancel()
   }
   // Create a new CancelToken
   token = axios.CancelToken.source()
   try{
     const res = await axios(query, {cancelToken: token.token})
     const result = res.data
     return result;
   } catch(error) {
       if(axios.isCancel(error)) {
         // Handle if request was cancelled
         console.log('Request canceled', error.message);
       } else {
         // Handle usual errors
         console.log('Something went wrong: ', error.message)
       }
   }
 }
}

export const avoidUnnecessarySearch = makeRequestCreator();

问题:: 问题在于,即使一切正常,但是在utils.js文件中编写的用于在发出新请求之前取消所有先前请求的代码仍无法正常工作,并且我在搜索中键入的每个按键或字母都收到了网络请求-盒子。

我的意图是,如果我输入“ spiderman”,则应该只搜索蜘蛛侠,而不是“ s”或“ p”或“ i”或“ d”或“ e”或“ r”或“ m” ”或“ a”以及对这些的要求应立即取消,以避免网络负担。 任何见解在这里都会有所帮助。

1 个答案:

答案 0 :(得分:0)

我复制了完全相同的代码并在代码沙箱中运行。可以了
Codesandbox:https://codesandbox.io/s/inspiring-mountain-zgqqt
如您所见,当我键入spiderman时,所有其他请求都被取消,仅成功击中了单词spidermanAPI Request。如果您遇到任何问题,请告诉我。