首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过索引响应管理多维数组

通过索引响应管理多维数组
EN

Stack Overflow用户
提问于 2020-04-09 02:31:32
回答 1查看 28关注 0票数 0

我有一个问题:如何根据所选的索引更新(在本例中是添加或移除货物)多维数组。父数组已经成功,但我不知道子数组如何处理数据时,单击Add Cargo按钮以添加货物,然后单击Remove cargo按钮根据所选索引删除所有货物。

请帮帮忙。这是我的码箱码

抱歉,风景还不够好

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-09 04:06:42

您需要为添加和/或删除货物的功能提供索引。在函数中,通过在inputFields上映射来更新嵌套字段。在调用handleAddCargo时,传递index,在调用handleRemoveCargo时,传递indexfinalIndex,后者是货物数组索引。

代码语言:javascript
复制
const handleAddCargo = (parentFiledIndex) => {
        const updatedInputFields = inputFields.map((item, i) => {
            if(parentFiledIndex === i){
                return {...item, cargo: item.cargo.concat({
                        cargoId: '',
                        cargoDescription: "",
                        cargoHsCode: ""
                    })}
            }else{
                return item
            }
        });
        setInputFields(updatedInputFields);
        console.log("add by its index cargo here");
    };

    const handleRemoveCargo = (parentFiledIndex, cargoIndex) => {
        const updatedInputFields = inputFields.map((item, i) => {
            if(parentFiledIndex === i){
                return {...item, cargo: item.cargo.filter((cargo, c) => c !== cargoIndex)}
            }else{
                return item
            }
        });
        setInputFields(updatedInputFields);
        console.log("remove by its index cargo here");
    };

更新的工作解决方案在这里

https://codesandbox.io/s/reverent-bose-c2nkk

快速记录-

  • 在呈现列表时尽量不要使用数组索引。对于例如,使用一些库生成唯一的id。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61113038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档