如何阻止 axios 向 api 发送多个请求?
How to stop axios send multiple requests to an api?
我正在尝试在我的应用程序中创建一个自动完成输入字段。我从外部 API 获得建议。当我启动该应用程序时,很多呼叫被发送到 api 并且它们会继续发送,直到我停止该应用程序。我什至没有点击按钮,但是函数 getSuggestions 发送请求。为什么会这样?
import axios from "axios";
import { useEffect, useState } from "react";
import { Button, Form, Row, Col } from "react-bootstrap";
import constants from "../../constants";
function Autocomplete() {
const [suggestions, setSuggestions] = useState([]);
function getSuggestions(inputText) {
const config = {
params: { search_term: inputText, search_type: 'listings' },
headers: {
'x-rapidapi-host': 'zoopla.p.rapidapi.com',
'x-rapidapi-key': 'x'
}
};
axios.get(`${constants.baseUrl}auto-complete`, config)
.then(response => {
const suggestionsList = response.data.suggestions.map(x => x.value);
setSuggestions(suggestionsList);
console.log(suggestions);
})
}
useEffect(()=>{
getSuggestions('Oxford');
},[]);
return (
<Row className="d-flex align-items-center">
<Col>
<Form.Control type="text" placeholder="Area" />
</Col>
<Col>
<Button variant="primary" type="button" onClick={getSuggestions('Oxford')}>
Search
</Button>
</Col>
</Row>
);
}
export default Autocomplete;
您需要更改 onClick(在 return 内)
getSuggestions('Oxford')
至
() => getSuggestions('Oxford')
否则它将 运行 与您的 useEffect
一起在第一次渲染时立即
我正在尝试在我的应用程序中创建一个自动完成输入字段。我从外部 API 获得建议。当我启动该应用程序时,很多呼叫被发送到 api 并且它们会继续发送,直到我停止该应用程序。我什至没有点击按钮,但是函数 getSuggestions 发送请求。为什么会这样?
import axios from "axios";
import { useEffect, useState } from "react";
import { Button, Form, Row, Col } from "react-bootstrap";
import constants from "../../constants";
function Autocomplete() {
const [suggestions, setSuggestions] = useState([]);
function getSuggestions(inputText) {
const config = {
params: { search_term: inputText, search_type: 'listings' },
headers: {
'x-rapidapi-host': 'zoopla.p.rapidapi.com',
'x-rapidapi-key': 'x'
}
};
axios.get(`${constants.baseUrl}auto-complete`, config)
.then(response => {
const suggestionsList = response.data.suggestions.map(x => x.value);
setSuggestions(suggestionsList);
console.log(suggestions);
})
}
useEffect(()=>{
getSuggestions('Oxford');
},[]);
return (
<Row className="d-flex align-items-center">
<Col>
<Form.Control type="text" placeholder="Area" />
</Col>
<Col>
<Button variant="primary" type="button" onClick={getSuggestions('Oxford')}>
Search
</Button>
</Col>
</Row>
);
}
export default Autocomplete;
您需要更改 onClick(在 return 内)
getSuggestions('Oxford')
至
() => getSuggestions('Oxford')
否则它将 运行 与您的 useEffect
一起在第一次渲染时立即