ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript-使用Ramda镜头更改对象的值属性

2019-11-08 03:34:13  阅读:319  来源: 互联网

标签:ramda-js reactjs redux javascript


我想知道如何使用Ramda Lenses更改对象属性.

目前,我的状态很深:

buckets[
    blocks[
        messages[
            replies [
                {id: 0, text: 'text 0', value: 'simple value 0'},
                {id: 1, text: 'text 1', value: 'simple value 1'},
                {id: 2, text: 'text 2', value: 'simple value 2'},
                ...
            ]
        ]
    ]
]

我有一个基本的有效载荷.我想获取属性和值,并在我的状态下用新值设置旧值,例如使用此有效负载:

{text: ‘new_text’}
or
{value: ‘new_value’}

在我的减速器中,我有:

case SEQUENCES.UPDATE_REPLY_ON_BLOCK :
// payload => {text: 'new_text'}, or {value: 'new_value'}, or anyway...

let key = Object.keys(payload)[0];
let value = payload[key];

return R.over(
  R.lensPath(["buckets", 0, "blocks", 0, "messages", 0, "replies", 0, key]),
  R.set(value),
  state
);

我尝试了Merge:

return R.over(
    R.lensPath(["buckets", 0, "blocks", 0, "messages", 0, "replies", 0),
    R.merge(payload),
    state,
);

但结果相同:状态未修改,我没有错误.

Maybe SOLVED with mergeDeepLeft :

//payload => {value: 'new_value'}

return R.over(
    R.lensPath(["buckets", 0, "blocks", 0, "messages", 0, "replies", 0),
    R.mergeDeepLeft(payload),
    state,
);

解决方法:

你近了问题是R.setR.over用于两个不同的任务.您不需要在这里.相反,应该设置外部功能,第二个参数是要将镜头设置为的值:

const payload = {text: 'new_text'}
const key = Object.keys(payload)[0];
const value = payload[key];

const state = {buckets: [{blocks: [{messages: [{replies: [{id: 0, text: 'text 0', value: 'simple value 0'}, {id: 1, text: 'text 1', value: 'simple value 1'}, {id: 2, text: 'text 2', value: 'simple value 2'}]}]}]}]}

console.log(
    R.set(
        R.lensPath(['buckets', 0, 'blocks', 0, 'messages', 0, 'replies', 0, key]),
        value,
        state,
    )
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

当您要基于已经存在的值进行调整时,可以使用over,将函数从旧值传递到新值作为第二个参数.例如,R.over(myLens,R.toUpper,obj):

const payload = {text: 'new_text'}
const key = Object.keys(payload)[0];
const value = payload[key];

const state = {buckets: [{blocks: [{messages: [{replies: [{id: 0, text: 'text 0', value: 'simple value 0'}, {id: 1, text: 'text 1', value: 'simple value 1'}, {id: 2, text: 'text 2', value: 'simple value 2'}]}]}]}]}

console.log(
    R.over(
        R.lensPath(['buckets', 0, 'blocks', 0, 'messages', 0, 'replies', 0, key]),
        R.toUpper,
        state,
    )
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

标签:ramda-js,reactjs,redux,javascript
来源: https://codeday.me/bug/20191108/2005372.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有