Redux - 将Item添加到数组时出现连接新状态的问题

时间:2017-03-28 15:02:12

标签: javascript arrays redux react-redux reducers

目前我的reducer函数存在问题,它不会更新questionList.items数组。我不确定我在这里做错了所以如果有人能指出我正确的方向会很棒:)

以下是我遇到问题的代码片段。我的问题在于我的ADD_QUESTIONS操作它不会将数组中的现有项目与新项目连接。相反,它会覆盖数组中的现有项

const ADD_QUESTION = 'ADD_QUESTION';
const FETCH_QUESTIONS = 'FETCH_QUESTIONS';
const FETCH_QUESTIONS_SUCCESS = 'FETCH_QUESTIONS_SUCCESS';
const FETCH_QUESTIONS_FAILURE = 'FETCH_QUESTIONS_FAILURE';

const INITIAL_STATE = { 
  questionsList: {items: [{
    id: 2222,
    questionString: 'your name',
    rejected: true
  }], error:null, loading: false},
    newQuestion:{question:null, error: null, loading: false}, 
    activeQuestion:{question:null, error:null, loading: false}, 
    deletedQuestion: {question: null, error:null, loading: false},
};

const questionsReducer = (state = INITIAL_STATE, action) => {
  const { payload, type } = action;
  switch (type) {
  case FETCH_QUESTIONS:
      return { ...state, questionsList: {items:[], error: null, loading: true} }; 
    case FETCH_QUESTIONS_SUCCESS:
      return { ...state, questionsList: {items: action.payload, error:null, loading: false} };
    case ADD_QUESTION:
      /** PROBLEM LIES HERE */ 
      return { ...state, questionsList: { items: [...state, payload], error: null, loading: false } }
    default: return state
  }
}

export default questionsReducer;

我已经拍摄了我的redux devtools控制台的屏幕截图,希望能更好地展示我正在处理的问题。通过查看下面的图片,您将看到items数组中的初始项目在ADD_QUESTION触发时被替换。

Screen Shot 2017-03-28 at 10.58.08 AM.png

1 个答案:

答案 0 :(得分:3)

您正试图传播整个state,而不仅仅是问题列表:

return { ...state, questionsList: { items: [...state, payload], error: null, loading: false } }

您无法将对象传播到数组中。相反,只传播州的相关片段

return { ...state, questionsList: { items: [...state.questionsList.items, payload], error: null, loading: false } }