【问题标题】:Issue with async default value in React Material UI AutocompleteReact Material UI 自动完成中的异步默认值问题
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您的代码出错的原因如下:

      1] defaultValue 采用默认必须选择的值,不应将数组传递给此属性。

      2] 除非您的自动完成功能不是 multiple,否则无法将数组传递给 valueinputValue 属性。

      【讨论】:

        【解决方案3】:

        好的,我实际上能够完成这项工作。原来我使用了错误的道具。我刚刚将defaultValue 更改为value 并且它起作用了。

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

        【讨论】:

          猜你喜欢
          • 2018-04-27
          • 2022-01-09
          • 1970-01-01
          • 2021-01-04
          • 2021-11-12
          • 2021-04-05
          • 2021-01-14
          • 2022-12-23
          • 1970-01-01
          相关资源
          最近更新 更多