为什么我不能链接 state.get('something').filter 和 immutable.js?

Why can't I chain state.get('something').filter with immutable.js?

我做错了什么?

我想使用 get('..')filter 过滤 state 中的 steps 键,但我可以'设法做到这一点。

我有这个功能:

function visibleSteps(state) {
  return state.get('steps').filter((step) => {
    return step.display
  })
}

使用此示例进行测试时:

describe('visibleSteps', () => {
  it('should show the steps with display true and their title', () => {
     const state = Map({
        steps: {
            0: {
                display: false
            },
            1: {
                display: true,
                title: "A title"
            },
            2: {
                display: true,
            },
            3: {
               display: false,
            }
        }
    })

    expect(visibleSteps(state).size).to.equal(2)
  })
})

我收到这个错误:

TypeError: state.get(...).filter is not a function

男人会怎么做?

您收到此错误是因为 steps 的值是普通对象。对象没有 .filter 方法。如果你希望值是一个Map,你可以显式地创建它:

const state = Map({
  steps: Map({
    // ...
  })
});

对于最内部的对象也是如此。如果你想将一个嵌套的JS object/array 深度转换为一个不可变的MapList,你可以使用immutable.fromJS.