我想知道如何使用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'} 要么 {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,
);
但结果相同:状态未修改,我没有错误。
也许可以通过mergeDeepLeft解决:
//payload => {value: 'new_value'}
return R.over(
R.lensPath(["buckets", 0, "blocks", 0, "messages", 0, "replies", 0),
R.mergeDeepLeft(payload),
state,
);
答案 0 :(得分:3)
您已经关闭。问题是R.set
和R.over
用于两个不同的任务。您在这里不需要over
。相反,您的外部函数应该为set
,第二个参数为您要将镜头设置为的值:
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>