![](/img/trans.png)
[英]Uncaught TypeError: Cannot read properties of undefined (reading 'name') - ReactJS
[英]Uncaught TypeError: Cannot read properties of undefined (reading 'name') | Material UI
我正在尝试在 MUI Autocomplete 上查看获取的数据,但我得到了这个错误,我不知道为什么,统计数据是从 MongoDB 获取的,我只是想查看类别的名称作为选项。
编码:
export default function ChooseCat() {
const [categories, setCats] = useState([]);
useEffect(() => {
const getCats = async () => {
const res = await axios.get("/categories");
setCats(res.data);
};
getCats();
}, []);
console.log(categories)
return(
<div>
<Autocomplete
multiple
id="tags-standard"
options={categories}
getOptionLabel={(c) => c.name}
defaultValue={[categories[3]]}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label="Multiple values"
placeholder="Favorites"
/>
)}
/>
</div>
)
}
您可以为自动完成选项添加无效合并运算符 (??)。 适用于选项为空或服务器响应有错误的情况。 还有一件事,自动完成的选项应该是对象数组,然后您可以为选项标签设置名称属性。
export default function ChooseCat() {
const [categories, setCats] = useState([]);
useEffect(() => {
const getCats = async () => {
const res = await axios.get("/categories");
setCats(res.data);
};
getCats();
}, []);
console.log(categories)
return(
<div>
<Autocomplete
multiple
id="tags-standard"
options={categories ?? [] }
getOptionLabel={(c) => c.name}
defaultValue={[categories[3]]}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label="Multiple values"
placeholder="Favorites"
/>
)}
/>
</div>
)
}
所以我添加了这个并且它起作用了getOptionLabel={option => (option ? option.name : "")}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.