我想知道如何使用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.set
和R.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>