Redux中的ImmutableJS:Uncaught TypeError:oldArr.push不是函数

时间:2017-09-27 14:27:59

标签: javascript arrays reactjs redux immutable.js

我有这个减速器:

import Immutable, { Map, Record} from 'immutable'
const tags = Map({ primary: ['tag1','tag2','tag3'], secondary: [] });

export default function (state=tags, action) {
  switch (action.type) {
      case 'ADD_PRIMARY_TAG': {
        //not sure about this:
        var oldArr = state.get('primary');
        var newArr = oldArr.push(action.payload)
        var newState = tags.set('primary', newArr);
        return newState;
      }
      default:
        console.log("Default Tags Reducer.");
      return state;
    }
}

但是,我不确定这一点。所以我有一个不可变的Map,在那里我有一个名为primary的数组,其中包含一些标签。现在我想在现有数组中添加一个标签。所以我用state.get('primary');获取当前数组,我将某些东西推入它的副本,然后我将新状态设置为新数组并返回它。

我不知道我哪里出错了,或者我是否正在以错误的方式使用Immutable。

当我运行时,我收到以下错误:

  

未捕获的TypeError:oldArr.push不是函数       at exports.default(index_bundle.js:44134)       在组合(index_bundle.js:32954)       在派遣(index_bundle.js:18293)       在index_bundle.js:44171       at Object.addPrimaryTag(index_bundle.js:32975)       在PhraseView.tagsSubmit(index_bundle.js:33813)       at Object.ReactErrorUtils.invokeGuardedCallback(index_bundle.js:6380)       在executeDispatch(index_bundle.js:4920)       at Object.executeDispatchesInOrder(index_bundle.js:4943)       at executeDispatchesAndRelease(index_bundle.js:3439)       在executeDispatchesAndReleaseTopLevel(index_bundle.js:3450)

我在这里使用数组的方式(在ImmutableJS的上下文中)可能是完全错误的吗?在我的不可变映射中对数组进行Shoudl是其他不可变对象吗?或者这个错误是怎么产生的?

2 个答案:

答案 0 :(得分:0)

您需要使用concat()代替push()

  

concat()方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

变化:

var newArr = oldArr.push(action.payload);

要:

var newArr = oldArr.concat([action.payload]);

答案 1 :(得分:0)

我只是尝试了以下内容并通过了:

import Immutable, {Map} from 'immutable'

describe('immutable tests', () => {
  it('Immutable array', () => {
    const tags = Map({ primary: ['tag1','tag2','tag3'], secondary: [] });
    let oldArr = tags.get('primary');
    oldArr.push('blabla')
    expect(oldArr).toHaveLength(4)
  })
})

您确定传入状态是您所期望的吗?也许它有一些其他的结构,从堆栈跟踪它不是很清楚什么调用你的减速机