簡體   English   中英

Redux中的ImmutableJS:未捕獲的TypeError:oldArr.push不是函數

[英]ImmutableJS in Redux : Uncaught TypeError: oldArr.push is not a function

我有這個減速器:

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');獲得了當前數組state.get('primary'); ,我將某些內容推入它的副本中,然后將新狀態設置為新數組並返回它。

我看不到我要去哪里錯了,也看不到我是否以錯誤的方式使用了Immutable。

當我運行它時,出現以下錯誤:

Uncaught TypeError:oldArr.push在exports.default(index_bundle.js:44134)處在組合(index_bundle.js:32954)在調度時(index_bundle.js:18293)在index_bundle.js:44171在Object.addPrimaryTag( index.bundle.js:32975)位於PhraseView.tagsSubmit(index_bundle.js:33813)位於Object.ReactErrorUtils.invokeGuardedCallback(index_bundle.js:6380)位於executeDispatch(index_bundle.js:4920)位於Object.executeDispatchesInOrder(index_bundle)處。在executeDispatchesAndRelease(index_bundle.js:3439)在executeDispatchesAndReleaseTopLevel(index_bundle.js:3450)

我在這里使用數組的方式(在ImmutableJS的上下文中)是否可能完全錯誤? 我的不可變映射中的數組應該是其他不可變對象嗎? 還是該錯誤如何產生?

您需要使用concat()而不是push()

concat()方法用於合並兩個或多個數組。 此方法不更改現有數組,而是返回一個新數組。

更改:

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

至:

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

我只是嘗試了以下方法而通過:

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)
  })
})

您確定傳入狀態是您期望的狀態嗎? 也許它具有其他結構,從堆棧跟蹤中還不清楚是什么調用了reducer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM