使用用户输入反应 axios api 调用
React axios api call with user input
我对反应还很陌生,我正在尝试使用 axios 根据用户输入进行 api 调用。我能够在表单提交时使用硬编码查询 ('cars') 获得结果,但我希望能够允许用户搜索不同的项目。我一直在研究如何将用户输入连接到 api 调用。
import axios from "axios";
import { useState, useEffect } from "react";
function App() {
const [data, setData] = useState([]);
const [userInput, setUserInput] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
axios({
url: "https://api.unsplash.com/search/photos",
method: "GET",
dataResponse: "json",
params: {
client_id: "d54vE8fu6bjJ_JgkBqugaZOt4bwFHGkmiKDGHunnXxc",
query: "cars",
per_page: 10,
},
}).then((response) => {
console.log(response.data.results);
setData(response.data.results);
});
};
return (
<div>
<form action="" onSubmit={handleSubmit}>
<label htmlFor="search">Search</label>
<input
id="search"
type="text"
value={userInput}
onChange={(event) => setUserInput(event.target.value)}
/>
</form>
<div>
{data.map((item) => {
return (
<div key={item.id}>
<img src={item.urls.thumb} alt="" />
</div>
);
})}
</div>
</div>
);
}
export default App;
你可以放query = userInput
const handleSubmit = (event) => {
event.preventDefault();
axios({
url: "https://api.unsplash.com/search/photos",
method: "GET",
dataResponse: "json",
params: {
client_id: "d54vE8fu6bjJ_JgkBqugaZOt4bwFHGkmiKDGHunnXxc",
query: userInput,
per_page: 10,
},
}).then((response) => {
console.log(response.data.results);
setData(response.data.results);
});
};