目前我的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
触发时被替换。
答案 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 } }