我正在使用“Material UI”自动完成组件在表单中呈现下拉列表。但是,如果用户想要编辑对象,则下拉列表应显示为自动填充从数据库中获取的任何值。
我尝试使用下面的代码来模拟这种情况
import React, { Component } from 'react';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';
export default class Sizes extends Component {
state = {
default: []
}
componentDidMount() {
setTimeout(() => {
this.setState({ default: [...this.state.default, top100Films[37]]})
})
}
render() {
return (
<Autocomplete
id="size-small-standard"
size="small"
options={top100Films}
getOptionLabel={option => option.title}
defaultValue={this.state.default}
renderInput={params => (
<TextField
{...params}
variant="standard"
label="Size small"
placeholder="Favorites"
fullWidth
/>
)}
/>
);
}
}
在安装组件后,我设置超时并返回应在下拉列表中显示的默认值
但是,它无法显示下拉列表中的值,并且我在控制台中看到此错误 -
index.js:1375 Material-UI: the `getOptionLabel` method of useAutocomplete do not handle the options correctly.
The component expect a string but received undefined.
For the input option: [], `getOptionLabel` returns: undefined.
显然,当调用 componentDidMount 时,状态正在更新,但 Autocomplete 组件的 defaultValue 属性无法读取相同内容
知道我在这里可能会犯什么错误吗?
代码沙箱链接 - https://codesandbox.io/s/dazzling-dirac-scxpr?fontsize=14&hidenavigation=1&theme=dark
最佳答案
对于遇到此问题的其他人来说,仅使用 value
而不是 defaultValue
的解决方案是不够的。一旦自动完成失去焦点,它就会恢复到原始值。
但是手动设置状态是可行的:
关于javascript - React Material UI 自动完成中的异步默认值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478421/