Immutabillity-helper-如何更新此值?

时间:2018-08-10 13:58:06

标签: javascript node.js immutability

我在“ aggRequest”中存储了一个json对象,这是我的json

{
    "state":{
       "controllerStates":[
       ],
       "rulesetStates":[
          {
             "rulesetContext":{
                "dialog_stack":[
                   {
                      "dialog_node":"root"
                   }
                ],
                "dialog_turn_counter":1,
                "dialog_request_counter":1,
                "_node_output_map":{
                   "node_1_1504607088493":[
                      0
                   ]
                },
                "branch_exited":true,
                "branch_exited_reason":"completed"
             },
             "convId":"XXXX",
             "modelRef":"XXXX"
          }
       ],
       "selfCallCount":0,
       "sysTurnCount":2,
       "userTurnCount":2
    },
    "context":{
       "conversationContext":{
          "brand":"XXXX",
          "channel":"XXX"
       },
       "userData":{
          "tokens":[
          ]
       }
    },
    "XXXXX":"2.0",
    "XXXXX":"XXXXX",
    "XXXXX":"XXXXX",
    "XXXXX":"XXXXX",
    "XXXXX":"XXXXX",
    "turnStart":"2018-08-10T15:21:36.075Z",
    "turnEnd":"2018-08-10T15:21:36.076Z"
 }

我正在尝试使用moment将turnEnd设置为新日期,日期创建正确,并且我认为我的功能是正确的-

    const update = require('immutability-helper');

    function updatePropertyValue() {
    const momentDateChange = getRunDateAsString();
    update(aggRequest, {
          $set:
            {
            turnEnd: `${momentDateChange}`,
            },
      });
     console.log(aggRequest)
}

当我查看addRequest console.log时,日期尚未更新...

有人有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

不变性的整个概念是您不能更改数据。相反,您创建一个新的。就像下面的示例一样:

const update = require('immutability-helper');

const data = {
  "turnEnd":"2018-08-10T15:21:36.076Z"
};

const newData = update(data, { $set: { turnEnd: 'voala!' } });

console.log(data); // it is immutable, right?
console.log(newData); // it is new version of the data

为了解决此问题,请更改代码以使用数据的更新(新版本):

const updateAggRequest = update(aggRequest, { $set: { turnEnd: momentDateChange } });