简体   繁体   English

Material UI React - 自动完成 - 如何重置内部 state

[英]Material UI React - Autocomplete - How to reset the internal state

My goal is to reset the internal state of Autocomplete Material-UI's component.我的目标是重置Autocomplete Material-UI 组件的内部 state。

My custom component is rendered N times in my cycle我的自定义组件在我的周期中被渲染了 N 次

{branches.map((branch, index) => {
    return (
        <BranchSetting
            key={index}
            index={index}
            data={branch}
            removeBranch={removeBranch}
        />

    )
})}

branch is my hook state.分支是我的钩子 state。

This is my removeBranch function:这是我的removeBranch function:

const removeBranch = (index) => {
    let listBranch = branches;
    listBranch.splice(index, 1);
    setBranches([...listBranch]);
}

Every time I delete an item to my array branch , everything works fine except the Autocomplete .每次我将一个项目删除到我的数组分支时,除了自动完成之外,一切正常。

This is my BranchSetting component:这是我的BranchSetting组件:

import React, { useState, useEffect } from "react";
import Autocomplete from '@material-ui/lab/Autocomplete';

const BranchSettings = ({ removeBranch, index, branchModify, data }) => {
    const [ brands, setBrands ] = useState(data.brands);

    const handleBrandSelected = (event, payload) => {
        const values = payload.map(item => item.value);
        setBrands(values);
    }

    useEffect(() => {
        setBrands(data.brands);
    }, [data])

    return (
        <>
            <Autocomplete
                id={'branch-brand'}
                multiple
                disableCloseOnSelect
                options={carsBrand}
                getOptionLabel={(carsBrand) => carsBrand.label}
                onChange={handleBrandSelected}
                renderTags={(value, getTagProps) =>
                    value.map((option, index) => (
                        <Chip
                            variant="outlined"
                            label={option.value}
                            size="small"
                            {...getTagProps({ index })}
                        />
                    ))
                }
                renderInput={(params) => {
                    return (
                        <TextField
                            {...params}
                            variant="filled"
                            fullWidth
                            label={'brand'}
                        />
                    )
                }}    
            />
        </>
    )
}
export default BranchSettings

carsBrand it is my data source that in the example I avoided writing the population. carsBrand这是我的数据源,在示例中我避免写入人口。 It's an array这是一个数组

Everytime I try to delete an item, Autocomplete keep the state of the component ad the prev position.每次我尝试删除一个项目时,自动完成功能都会保留组件的 state 和上一个 position。 I'm looking a way to reset all the internal state of Autocomplete component.我正在寻找一种方法来重置自动完成组件的所有内部 state。 The status I refer to can be seen with the devToolBar我指的状态可以用devToolBar看到

在此处输入图像描述

I'm looking a good way to keep the items selected properly or that every time the component has changed, rerender the Autocomplete component.我正在寻找一种保持正确选择项目的好方法,或者每次组件更改时,重新渲染自动完成组件。

I resolved the problem.我解决了这个问题。

The problem was that Autocomplete component need to input an array of objects with label and value keys.问题是自动完成组件需要输入带有label键的对象数组。

In the function handleBrandSelected I saved into my brands status just the value.在 function handleBrandSelected 中,我将值保存到我的品牌状态中。 I should have saved the whole object because then it must be sent as input in Autocomplete with the props value .我应该保存整个 object 因为它必须作为输入在Autocomplete中与 props一起发送。 And to handle the object I should have also used props getOptionSelected .为了处理 object 我还应该使用道具getOptionSelected

No problems with the remove function, and no problems with indexes.删除 function 没有问题,索引也没有问题。 Only the values selected in inputs and compliant with the documentation were missing.仅缺少在输入中选择并符合文档的值。 So this is the new code所以这是新代码

import React, { useState, useEffect } from "react";
import Autocomplete from '@material-ui/lab/Autocomplete';

const BranchSettings = ({ removeBranch, index, branchModify, data }) => {
    const [ brands, setBrands ] = useState(data.brands);

    const handleBrandSelected = (event, payload) => setBrands(payload);

    useEffect(() => {
        setBrands(data.brands);
    }, [data])

    return (
        <>
            <Autocomplete
                id={'branch-brand'}
                multiple
                disableCloseOnSelect
                options={carsBrand}
                getOptionLabel={(carsBrand) => carsBrand.label}
                onChange={handleBrandSelected}
                renderTags={(value, getTagProps) =>
                    value.map((option, index) => (
                        <Chip
                            variant="outlined"
                            label={option.value}
                            size="small"
                            {...getTagProps({ index })}
                        />
                    ))
                }
                renderInput={(params) => {
                    return (
                        <TextField
                            {...params}
                            variant="filled"
                            fullWidth
                            label={'brand'}
                        />
                    )
                }}
                getOptionSelected={(option, value) => option.value === value.value}
                value={brands}  
            />
        </>
    )
}
export default BranchSettings

This problem is probably caused by using the array index as a key in <BranchSetting key={index} .此问题可能是由于在<BranchSetting key={index}中使用数组索引作为键引起的。 I recommend that you add a unique id when creating the branch object, and use that id as a key instead.我建议您在创建branch object 时添加唯一 id,并使用该 id 作为键。 You can use performance.now() or a small lib like nanoid .您可以使用performance.now()nanoid 之类的小库。

You can read more about the negative impacts of using an index as a key here .您可以在此处阅读有关使用索引作为键的负面影响的更多信息。

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

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