【问题标题】:React filtered array of values is not getting updated in the dropdown,however is in fact updated in console.logReact 过滤的值数组没有在下拉列表中更新,但实际上在 console.log 中更新
【发布时间】:2021-07-26 15:39:58
【问题描述】:

我有两个下拉列表,第二个是根据第一个中选择的值填充的。 选择第一个下拉列表中的值后,将根据第一个下拉列表中所选选项的值过滤第二个下拉列表的选项数组。

当应用程序加载并在第一个下拉列表中选择第一个值时,选项被正确过滤,但是如果我关闭下拉列表并再次选择相同的第一个选项,过滤结果不会在第二个下拉列表中更新,但它们仍然作为正确的过滤结果出现在 console.log 中。

这是一个代码示例:

function MyForm(){

const [optValue,setOptValue] = React.useState('');

const options = [
{key:'testvalue',text:'testvalue',value:'testvalue'},
{key:'anotherTestvalue',text:'anotherTestvalue',value:'anotherTestvalue'},
]

const options2 = [
{key:'testvalue',text:'update',value:'update'},
{key:'testvalue',text:'delete',value:'delete'},
{key:'anotherTestvalue',text:'modify',value:'modify'},
{key:'anotherTestvalue',text:'create',value:'create'},
]
const filteredOptions = options2.filter(el => {
let opValue;

if (optValue == 'testvalue') {
opValue = el.key === 'testvalue'

} else if (optValue == 'anotherTestvalue') {
 opValue= el.key === 'anotherTestValue'
}

return opValue;

});

return (

<UI.Form.Field
control={Select}
options={options}
onChange={(e,{value}) => {
setOptValue(value);
}}
/>

<UI.Form.Field
control={Select}
options={filteredOptions}

/>
)
}

所以,一旦我打开表单并在第一个下拉列表中选择第一个值,第二个显示两个值:更新和删除。如果我在第一个下拉列表中选择第二个值,第二个显示两个值:创建,修改。但是,如果我再次选择第一个下拉列表中的第一个值,尽管过滤器正在工作,但第二个下拉列表中的值仍然存在

附: 我正在使用语义 UI 来设置表单样式

【问题讨论】:

    标签: javascript reactjs react-hooks semantic-ui semantic-ui-react


    【解决方案1】:

    我看到的很容易解决,你需要调用一个 useEffect 来检查第一个选择器的值,然后在 useEffect 中更改过滤器的数据,它会正常工作。

    useEffect( ()=>{
    //Here call the filter function and charge it into a state to be sure
    // that render will update. 
    }),[optValue]}
    

    【讨论】:

    • 感谢您的帮助。刚做了,还是没有更新
    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    相关资源
    最近更新 更多