繁体   English   中英

如何将数组 object 转换为与 MUI 的自动完成字段一起使用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM