【问题标题】:How can I update nested immutable in reducer?如何更新减速器中的嵌套不可变?
【发布时间】:2017-07-19 18:40:07
【问题描述】:

我对 immutable.js 很陌生。 我要更新home.filmList[0].isDetailModalShow = false. 我该怎么做? 请帮我! 我的状态是这样的:

{
  home: {
    filmList: [
      {
        id: 1,
        name: '111',
        imgUrl: '111',
        isDetailModalShow: false
      },
      {
        id: 2,
        name: '222',
        imgUrl: '',
        isDetailModalShow: false
      },
    ]
  }
}

和我的减速机这样

import { createReducer } from 'redux-act'
import { fromJS } from 'immutable'
import { setFilmList, toggleDetailModal } from './actions'

const initialState = fromJS({
  filmList: [],
})

export default createReducer({
  [toggleDetailModal]: (state, payload) => {
    const index = state.get('filmList').findIndex(item => item.id === payload)
    // state.get(filmList) is filmList: [........]
    // below line code do not work!
    return state.updateIn(['filmList', index, 'isDetailModalShow'], value => !value)
  },
}, initialState)

【问题讨论】:

    标签: reactjs redux immutable.js


    【解决方案1】:

    你可以使用 Immutable 的 setIn 函数:

    state.setIn(['filmList', 0, 'isDetailModalShow'], false)

    【讨论】:

    • 它警告未捕获的错误:无效的 keyPath
    【解决方案2】:

    我找到了解决方案...

    当我设置filmList

    我忘了用fromJS

    // old
    [setFilmList]: (state, payload) => {
      return state.set('filmList', payload)
    }
    // new, it works!
    [setFilmList]: (state, payload) => {
      return state.set('filmList', fromJS(payload))
    }

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      相关资源
      最近更新 更多