[英]How to get specific object key in array using MUI multiple autocomplete and useState hook?
[英]How to convert a array object to use with MUI's Autocomplete field
我正在嘗試將傳入的 object 轉換為 MUI 的 Autcomplete object 可用的東西,但是,我正在努力做到這一點。
我目前的代碼如下:
const [contactList, setContactList] = useState([]);
useEffect(() => {
fetch(CONTACTS_URL, {
method: "GET",
headers: {"Authorization": sessionStorage.getItem("accessToken")}
})
.then((response) => response.json())
.then((responseData) => {
setContactList({responseData});
})
.catch((error) => console.error(error));
}, [])
打印到控制台時會產生以下內容:
Object
responseData: Array(1)
0:
{
contactId: 1,
contactName: 'Cool Contact',
firstLetter: "C"
}
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object
Autocomplete 的文檔說我需要這樣做:
const options = top100Films.map((option) => {
const firstLetter = option.title[0].toUpperCase();
return {
firstLetter: /[0-9]/.test(firstLetter) ? '0-9' : firstLetter,
...option,
};
});
<Autocomplete
id="grouped-demo"
options={options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))}
groupBy={(option) => option.firstLetter}
getOptionLabel={(option) => option.title}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="With categories" />}
/>
然而,上面的例子給人的印象是你正在使用一個已經預定義的常量,而我的不是這樣。
我將如何 go 將我的東西轉換成自動完成可以使用的東西?
只需將 contactList 傳遞給options
屬性,並為getOptionLabel
提供回調。
並且,無需使用 object 調用setContactList
,只需直接傳遞數組即可。 這樣, contactList
就是一個選項數組。
const [contactList, setContactList] = useState([]);
useEffect(() => {
fetch(CONTACTS_URL, {
method: 'GET',
headers: { Authorization: sessionStorage.getItem('accessToken') },
})
.then((response) => response.json())
.then((responseData) => {
setContactList(responseData);
})
.catch((error) => console.error(error));
}, []);
return (
<Autocomplete
options={contactList}
getOptionLabel={(contact) => contact.contactName}
/>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.