如何访问蚂蚁选择键的值

问题描述 投票:0回答:1

[我需要获取所选item IDitem,在我的情况下,用户输入输入并从API中获取数组的形式的结果,该数组将迭代<Option>,如下所示。

<Select
    mode="multiple"
    style={{ width: '100%' }}
    placeholder="Select Invoices"
    defaultValue={[]}
    onChange={handle_select_invoices}
    optionLabelProp="label"
    onSearch={search_invoice_by_number}
    >
    {
    invoices.map((el,index) => {
        return <Option key={el.invoice_id} value={el.invoice_number}></Option>
    })
    }
</Select>

当用户选择一个选项时,会触发handle_select_invoices。它需要两个参数valuekey

const handle_select_invoices =(value,key) => {
    console.log(' ************** IDS ****************')
    console.log(key)
}

function search_invoice_by_number(value) {
    var data={'invoice_number':value};
    axios.post('http://localhost:4000/get_invoice_by_number',data).then(
        response => {

            if(response.data.length > 0){
                set_invoices(response.data);
            }else{
                set_invoices([]);
            }
        },error =>{
            Swal.fire({
                title: 'Error!',
                text: 'Please Contact your software developer',
                icon: 'error',
                confirmButtonText: 'OK'
            })
        }
    )
}

问题

[当用户选择多个项目时,console.log显示空的Json元素,并且仅填充数组中的最后一个元素。

console.log from handle_select_invoices method that is executed on the onChange event

导致此结果的代码有什么问题?

javascript reactjs antd multi-select
1个回答
0
投票

[好,我想我明白你的意思。我建议您这样做。使用状态为selectedValues的变量。在选择onChange中,只需将它们设置为类似于handleChange = values => setSelectedValues(values)的状态。在搜索中,从API获取新数据后,按如下所示过滤selectedValues

set_invoices(response.data);
const values = selectedValues.filter(value => 
    data.map(i => i.invoice_number).includes(value)
);
setSelectedValues(values); // filter out the values that do not exist in the new data

并且您的选择将包含一个额外的道具value={selectedValues}

这是带有一些伪数据的有效示例:https://codesandbox.io/s/pedantic-carson-xwydd?file=/src/App.js:699-805

© www.soinside.com 2019 - 2024. All rights reserved.