React Material UI Autocomplete 中的异步默认值问题

tru*_*hit 4 javascript reactjs material-ui

我正在使用“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
                        />
                    )}
                />
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里安装组件后,我设置超时并返回应显示在下拉列表中的默认值

但是,它无法在下拉列表中显示该值,并且我在控制台中看到此错误 -

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.
Run Code Online (Sandbox Code Playgroud)

显然,当 componentDidMount 被调用时状态正在更新,但自动完成组件的 defaultValue 道具无法读取相同的内容

知道我在这里可能会出错吗?

代码沙箱链接 - https://codesandbox.io/s/dazzling-dirac-scxpr?fontsize=14&hidenavigation=1&theme=dark

Dal*_*ing 5

对于遇到此问题的任何其他人,仅使用value而不是解决方案defaultValue是不够的。一旦自动完成失去焦点,它将恢复到原始值。

但是,手动设置状态将起作用:

https://codesandbox.io/s/elegant-leavitt-v2i0h


tru*_*hit 1

好吧,我实际上能够完成这项工作。原来我使用了错误的道具。我刚刚更改defaultValuevalue并且有效。

更新了代码笔链接 -codesandbox.io/s/dazzling-dirac-scxpr