javascript - React Material UI 自动完成中的异步默认值问题

标签 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
                        />
                    )}
                />
        );
    }
}

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

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

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 的解决方案是不够的。一旦自动完成失去焦点,它就会恢复到原始值。

但是手动设置状态是可行的:

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

关于javascript - React Material UI 自动完成中的异步默认值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478421/

相关文章:

javascript - 在与 Material UI <TextField/> 一起使用时将 'label' Prop 传递给 Formik <Field/>

reactjs - 我如何限制可以在 Material UI 实验室自动完成组件中选择的最大选项数

javascript - 恶意 JavaScript 代码

javascript - 当我们在 Javascript 中重新声明对象时会发生什么?

javascript - 如何在不同的组件中压缩相同的导入语句(遵循 DRY 指南)

javascript - 模拟服务 worker ,悲伤的路径测试失败

javascript - 如何使用 JSFiddle 在浏览器中计算所有具有很大最大值的素数

javascript - 如何获取对象中 bool 值的计数

javascript - React 处理空 props

javascript - 子组件中的函数不能在父组件中设置状态