【发布时间】:2020-04-16 02:32:35
【问题描述】:
我正在使用“材料 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 被调用时状态正在更新,但自动完成组件的 defaultValue 道具无法读取相同
知道我在这里可能会出错吗?
代码沙盒链接-https://codesandbox.io/s/dazzling-dirac-scxpr?fontsize=14&hidenavigation=1&theme=dark
【问题讨论】:
标签: javascript reactjs material-ui