我在反应功能组件中有这种搜索方法,在每次按下按键时,我都会执行网络请求。如果立即执行新操作,我会尝试取消先前的请求。不幸的是,此代码不会取消请求。有人可以向我解释原因吗?
let source
async function search(inputValue) {
// Check if we made a request
if (source) {
// Cancel the previous request before making a new request
source.cancel('Operation canceled due to new request.')
}
// Create a new CancelToken
source = axios.CancelToken.source()
try {
searchMovies(inputValue, { cancelToken: source.token }).then(filteredMovies => {
dispatch({ type: "FILTERED_MOVIES", filteredMovies })
})
} 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)
}
}
}
我的searchMovies
实现是这样的:
export const searchMovies = async (query = "", options, page = 1) => {
const { data = {} } = await axios(
`https://api.themoviedb.org/3/search/movie?api_key=${process.env.REACT_APP_API_KEY}&language=en-US&query=${query}&page=${page}&include_adult=false`
, { ...options })
const formatedData = data.results.map(movie => {
let title = movie.original_title || movie.original_name || movie.title || ""
return {
poster_path: `http://image.tmdb.org/t/p/w400/${movie.poster_path}`,
title,
id: movie.id
}
})
return formatedData
}