简体   繁体   English

React.js状态项数组未正确更新,甚至没有显示任何错误

[英]React.js state items array not updating properly even not showing any error

At first please see the picture for actually what's going on 首先请看图片,看看究竟发生了什么

在此输入图像描述

The issue is while marked the checkbox then text erasing but I want to update a state field from state array & the functionalities are like below 问题是标记复选框然后文本擦除但我想从状态数组更新状态字段,功能如下

state = {
    items: [
        { id: 1, text: 'Buy milk', done: true },
        { id: 2, text: 'Deed cat', done: false },
        { id: 3, text: 'Wash floor', done: false }
    ]
};

markItemDone = (i) => {
    this.setState(state => {
        const items = state.items.map((item) => {
            if (item.id === i){
                return item.done = true;
            } else {
                return item;
            }
        });

        return {
            items,
        };
    });
}

JSX: JSX:

 <input 
    type="checkbox" 
    onClick={() => this.markItemDone(item.id)}
    defaultChecked={item.done ? true : null}
 />

I'm not finding the actual solution. 我找不到实际的解决方案。

Thanks 谢谢

In your code, you say return item.done = true; 在你的代码中,你说return item.done = true; . This is returning a boolean instead of an item object and thus why you see 1: true in your screenshot. 这是返回布尔值而不是项目对象,因此您在屏幕截图中看到1: true原因。 Instead, you want something like this: 相反,你想要这样的东西:

        if (item.id === i){
            return {
                ...item,
                done: true,
            };
        } else {
            return item;
        }

This will make a copy of the original item object, set its done field to be true , and return the new item. 这将生成原始项目对象的副本,将其done字段设置为true ,并返回新项目。

This line in your map callback: map回调中的这一行:

return item.done = true; 

will map item to undefined for the item where id === i . item映射到undefinedid === iitem Try revising your map callback as shown: 尝试修改您的map回调,如下所示:

const items = state.items.map((item) => {

    /* Return copy of item. If id === item.id, add done : true to 
        mapped result. For all other cases, ensure done is undefined */ 
        return { ...item, done : id === item.id ? true : undefined };

});

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

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