更新数组中的嵌套对象时,不变性助手将返回未定义的

时间:2018-09-21 08:13:02

标签: arrays reactjs react-native immutability immutability-helper

我有以下数组:

usage: [
  {date: '2018-09-21', appliedNight: false, appliedDay: false, time: 'day'},
  {date: '2018-09-20', appliedNight: true, appliedDay: false, time: 'day'}
]

按一下按钮,我尝试在数组内转换对象:

transformEntry = (item, index, time) => {
    this.setState(update(this.state, {
            products: {
                [index]: {
                    usage: {
                        $apply: (items) => {
                            if (items.length > 0) {
                                items.map((usage) => {
                                    if (usage.date === this.state.currentDate) {
                                        return {
                                            ...usage,
                                            date        : this.state.currentDate,
                                            appliedNight: time === 'night',
                                            appliedDay  : time === 'day',
                                            time        : time
                                        };
                                    } else return items;
                                });
                            }
                            else {  // if no items found
                                let newUsage = {
                                    usage: {
                                        date        : this.state.currentDate,
                                        appliedNight: time === 'night',
                                        appliedDay  : time === 'day',
                                        time        : time
                                    }
                                };
                                return Object.values(newUsage);
                            }
                        }
                    }
                }
            }
        }
    ));
};

newUsage部分按预期工作,如果array为空,它将创建一个对象。问题出在第一部分,当数组不为空时,它总是将数组设置为未定义。

我也尝试更新从map返回的用法,但同样,未定义:

if (usage.date === this.state.currentDate) {
    return update(usage, {
       $set: {
           date        : this.state.currentDate,
           appliedNight: time === 'night',
           appliedDay  : time === 'day',
           time        : time
              }
         });
  }

我正在使用immutability-helper@2.8.1

裸露的最小游乐场:codesandbox

0 个答案:

没有答案