![](/img/trans.png)
[英](React-Select hooks) How can I update state using Select's onChange render prop?
[英](React-Select hooks) state not changing when React-Select onChange prop handling
我已經嘗試了很多方法,但我無法通過 onChange 更新 userSearchSuggestion state。 我正在開發一個搜索欄組件,該組件在用戶未更改搜索欄輸入 3 秒后進行 fetch 調用,但似乎在將文本添加到組件時 onChange 根本沒有觸發。 這是代碼:
import React, { useState, useEffect } from "react";
import Select from "react-select";
export default function SearchBar() {
const [userSearchInput, setUserSearchInput] = useState("");
const [searchSuggestions, setSearchSuggestions] = useState([]);
useEffect(() => {
const searchSuggestions = async (searchInput) => {
console.log("api called");
const searchSuggestions = await fetch(
"API STUFF"
)
.then((response) => response.json())
.then((data) => {
setSearchSuggestions(data.quotes);
});
};
const timer = setTimeout(() => {
if (userSearchInput !== "") {
searchSuggestions(userSearchInput);
}
}, 3000);
return () => clearTimeout(timer);
}, [userSearchInput]);
return (
<Select
value={userSearchInput}
options={searchSuggestions}
onChange={(e) => setUserSearchInput(e.currentTarget.value)}
placeholder="Search a ticker"
/>
);
}
關於為什么 onChange 不更新 state 的任何想法? 即使我只是在 onChange 上使用 console.log(e),也沒有任何內容記錄到控制台中。
如果您想在用戶輸入Select
輸入時調用 API,請使用onInputChange
而不是onChange
。
onChange
。onInputChange
。<Select onInputChange={(input) => console.log(input)}
我還看到您想在用戶鍵入時稍微延遲 API 調用。 這是一個很好的做法,但傳統的做法是使用debounce
或throttle
。 你可以在這里看到它們之間的不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.