admin管理员组文章数量:1327997
I'm trying to use ImmutableJS's reduce function like so:
const myChanges = data
.getIn(['a', 'b']) // Immutable.List
.reduce((accum, data) => {
// console.log('accum', accum);
// console.log('data', data); <--- an Immutable.Map
accum.push(List([ data.get('id'), data.get('time') ]));
return accum;
}, List());
However, accum
always console logs as an empty Immutable.List. My guess is that it's because List() can't be mutated, so each time accum
is returning a new empty Immutable.List().
What I would like to get is a list of lists, where each of the inner lists (essentially a tuple) consists of id
and time
.
How can I get this to work? Do I need to use withMutations
?
I'm trying to use ImmutableJS's reduce function like so:
const myChanges = data
.getIn(['a', 'b']) // Immutable.List
.reduce((accum, data) => {
// console.log('accum', accum);
// console.log('data', data); <--- an Immutable.Map
accum.push(List([ data.get('id'), data.get('time') ]));
return accum;
}, List());
However, accum
always console logs as an empty Immutable.List. My guess is that it's because List() can't be mutated, so each time accum
is returning a new empty Immutable.List().
What I would like to get is a list of lists, where each of the inner lists (essentially a tuple) consists of id
and time
.
How can I get this to work? Do I need to use withMutations
?
2 Answers
Reset to default 5In immutable all data are 'readonly'. When you call the push method it returns a new object with the changes. For this code to work you need to return directly:
const myChanges = data.getIn(['a', 'b'])
.reduce((accum, data) => {
return accum.push(List([ data.get('id'), data.get('time') ]));
}, List());
or you can store the result in a variable and return it
const myChanges = data.getIn(['a', 'b'])
.reduce((accum, data) => {
let result = accum.push(List([ data.get('id'), data.get('time') ]));
return result;
}, List());
Your problem is that you return the original accum
, not the new value that includes the data. Remember that push
returns a new list, unlike a mutable JS Array
!
const myChanges = data
.getIn(['a', 'b'])
.reduce((accum, d) => {
return accum.push(List([ d.get('id'), d.get('time') ]));
}, List());
本文标签: javascriptHow to use ImmutableJS39s reduce function with an Immutable accumulatorStack Overflow
版权声明:本文标题:javascript - How to use ImmutableJS's reduce function with an Immutable accumulator? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742242352a2438913.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论