如何返回Redux reducer的对象数组状态

时间:2016-09-16 17:49:22

标签: reactjs redux

有这样的州:

 review: {
    "amount": 217,
    "snippets": [
      {
       "id": 0,
       "flag": false
      },
      {
       "id": 1,
       "flag": false
      },
      ...
    ]
  }

现在如果我只想设置review.snippets [1] .flag = true,那么应该在reducer中写什么? 例如:

case SET_FLAG: return {
    ...state,
    review: {
      ...state.review,
      snippets: {
        ...state.review.snippets,
        // don't know how to write here to express array
      }
    },
};

1 个答案:

答案 0 :(得分:0)

如果您没有使用combineReducers来分隔商店的各个部分,那么您可以将减速器案例保持相似,但是对片段数组执行此类操作

// grab your snippets
const snippets = state.review.snippets

// create a copy
const snippetsCopy = snippets.slice()

// replace the element with a new object with the same properties
// and overwrite the property you want
snippetsCopy[1] = {
  ...snippetsCopy[1],
  flag: true
}
const newSnippetsArray = Object.assign(arr, newArr)

// in your switch case return something like this:

return {
    ...state,
    review: {
      ...state.review,
      snippets: newSnippetsArray
    },
};