简体   繁体   English

React、MUI 自动完成和 useState

[英]React, MUI AutoComplete and useState

I'm trying to implement AutoComplete component of MUI in React but i'm getting some errors, can't understand what am I doing wrong.我正在尝试在 React 中实现 MUI 的 AutoComplete 组件,但我遇到了一些错误,无法理解我做错了什么。

Those are the errors I get:这些是我得到的错误:

MUI: The value provided to Autocomplete is invalid.
None of the options match with `{"id":"2","name":"Delta Super","description":"Deltamethrin 0.025%"}`.
You can use the `isOptionEqualToValue` prop to customize the equality test.

This is my code:这是我的代码:

function PesticideAutoComplete(props) {

    const data = [
        {
            id: '1',
            name: 'Parmenona',
            description: 'Permethrin 0.020%',
        },
        {
            id: '2',
            name: 'Delta Super',
            description: 'Deltamethrin 0.025%',
        },
        {
            id: '3',
            name: 'Shoam',
            description: 'Bifenthrin 0.1%',
        }
    ];

    const defaultValue = { id: '1' };
    const [value, setValue] = useState(defaultValue);

    const defaultProps = {
        options: data,
        getOptionLabel: (option) => option.name,
    };

    return (
        <Autocomplete
            {...defaultProps}
            id="grid-choose-pesticide"
            clearOnEscape
            defaultValue={defaultValue}
            onChange={(event, newValue) => {
                console.log(newValue);
                setValue(newValue);
            }}
            renderInput={(params) => (
                <TextField {...params} label="Pesticide" />
            )}
        />
    );
}

I would not use the default prop if you want to put value use the options={} props to inject the values in to the ac component.如果您想输入值,我不会使用默认道具,请使用 options={} 道具将值注入到 ac 组件中。

 < Autocomplete options = {data} getOptionLabel={(option) => option.name} id = "grid-choose-pesticide" clearOnEscape defaultValue = { defaultValue } onChange = { (event, newValue) => { console.log(newValue); setValue(newValue); } } renderInput = { (params) => ( < TextField { ...params } label = "Pesticide" / > ) } />

You need to override isOptionEqualToValue in your element:您需要在元素中覆盖isOptionEqualToValue

<Autocomplete
    {...defaultProps}
    id="grid-choose-pesticide"
    clearOnEscape
    defaultValue={defaultValue}
    onChange={(event, newValue) => {
        console.log(newValue);
        setValue(newValue);
    }}
    renderInput={(params) => (
        <TextField {...params} label="Pesticide" />
    )}
    isOptionEqualToValue={(option, value) => option.id === value.id}
/>

The reason this happens is that the Autocomplete compares your selected object with a predefined one in the back.发生这种情况的原因是自动完成功能会将您选择的对象与后面的预定义对象进行比较。 You can see the full explanation in this post .你可以在这篇文章中看到完整的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM