从Redux中的数组中删除项目

时间:2017-10-24 13:48:16

标签: arrays object redux state reducers

我正在学习redux,我想知道如何从州中删除一个项目。我有这个初始状态:

export const getInitialState = () => {
  let state = {
    isLogged: false,
    organizations: [],
    userData: {},
    activeIndex: -1,
    currentRetrospective: {},
    hasFetched: false
  }

这就是数据在organizations

中的存在方式
  case `${actions.ACTION_GET_USER_ORGS}_FULFILLED`: {
    let activeIndex = 0
    if (state.activeIndex !== -1) {
      activeIndex = state.activeIndex
    } else if (action.payload.data.length === 0) {
      activeIndex = -1
    }
    return { ...state, activeIndex, organizations: action.payload.data, hasFetched: true }
  }

现在,我需要做的是从retrospectives中的organization数组中删除一个项目。我试过这个,但它不起作用。有没有更好的方法呢?

export default (state = getInitialState(), action) => {
  switch (action.type) {

  case `${actions.ACTION_DELETE_RETROSPECTIVE}_FULFILLED`: {

    const { organizations, activeIndex } = state

    const newOrganizations = JSON.parse(JSON.stringify(organizations))

    const activeOrganization = newOrganizations[activeIndex]

    activeOrganization.retrospectives = activeOrganization.retrospectives
      .filter((retro) => retro.id != action.retroId )

    return { ...state, organizations: newOrganizations }
  }

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以像这样过滤组织数组:

 export default (state = getInitialState(), action) => {
      switch (action.type) {
          case `${actions.ACTION_DELETE_RETROSPECTIVE}_FULFILLED`: {
              return { 
                  ...state, 
                  organizations: state.organization.filter(retro => 
                      retro.id !== action.retroId }
      }