MUI 自动完成默认值未显示?
import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
export default function ComboBox() {
const [top100Films, settop100Films] = React.useState([]);
const value = 1;
React.useEffect(() => {
fetch("https://reqres.in/api/users?page=1")
.then((res) => res.json())
.then(({ data }) => {
console.log(data);
settop100Films(data);
})
.catch((err) => console.log(err));
}, []);
// if (!top100Films.length > 0) {
// return "";
// }
return (
<Autocomplete
disablePortal
id="combo-box-demo"
defaultValue={
top100Films.find((ele) => ele.id === value) || null
}
options={top100Films}
getOptionLabel={(data) => data.first_name}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
/>
);
}
如果我取消注释此 if 条件,它就可以正常工作。但我不想要这种行为。最初 defalutValue 将为 null。获取数据后,默认值将更改为精确值。但该值未显示在自动完成中。
import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
export default function ComboBox() {
const [top100Films, settop100Films] = React.useState([]);
const value = 1;
React.useEffect(() => {
fetch("https://reqres.in/api/users?page=1")
.then((res) => res.json())
.then(({ data }) => {
console.log(data);
settop100Films(data);
})
.catch((err) => console.log(err));
}, []);
// if (!top100Films.length > 0) {
// return "";
// }
return (
<Autocomplete
disablePortal
id="combo-box-demo"
defaultValue={
top100Films.find((ele) => ele.id === value) || null
}
options={top100Films}
getOptionLabel={(data) => data.first_name}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
/>
);
}
If i uncomment this if condition it works fine. But i don't want that behaviour. Initially defalutValue will be null. After fetching data default value will be changed to the exact value. But the value not shown in autocomplete.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在defaultValue中你不应该使用console.log,你可以尝试这样:
In the defaultValue you should not use console.log, you can try like this: