weixin_33721344 2015-12-27 15:51 采纳率: 0%
浏览 242

用lodash更新json

Actually I need to handle mysite frontend fully with json objects(React and lodash).

I am getting the initial data via an ajax call we say,

starred[] //returns empty array from server

and am adding new json when user clicks on star buton it,

starred.push({'id':10,'starred':1});

if the user clicks again the starred should be 0

current_star=_findWhere(starred,{'id':10});
_.set(curren_star,'starred',0);

but when doing console.log

console.log(starred); //returns
[object{'id':10,'starred':0}]

but actually when it is repeated the global json is not updating,while am performing some other operations the json is like,

console.log(starred); //returns
[object{'id':10,'starred':1}]

How to update the global , i want once i changed the json, it should be changed ever.Should I get any idea of suggesting some better frameworks to handle json much easier.

Thanks before!

  • 写回答

2条回答 默认 最新

  • weixin_33675507 2016-03-20 18:12
    关注

    I think the problem is in mutating original state. Instead of making push, you need to do the following f.e.:

    var state = {
        starred: []
    };
    
    //perform push
    var newItem = {id:10, starred:1};
    state.starred = state.starred.concat(newItem);
    
    console.log(state.starred); 
    //{ id: 10, starred: 1 }]
    
    var newStarred = _.extend({}, state.starred);
    var curr = _.findWhere(newStarred, {id: 10});
    
    curr.starred = 0;
    
    state = _.extend({}, state, {starred: newStarred});
    
    console.log(state.starred)
    //{ id: 10, starred: 0 }]
    

    To solve this in a more nice looking fashion, you need to use either React's immutability helper, or ES6 stuff, like: {...state, {starred: []}} instead of extending new object every time. Or just use react-redux =)

    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加