簡體   English   中英

未捕獲的不變違規:使用 arrayMove 時在調度之間檢測到 state 突變

[英]Uncaught Invariant Violation: A state mutation was detected between dispatches when using arrayMove

我正在嘗試構建一個 React/Redux 應用程序,我是一個初學者。 我想使用 React Sortable HOC 來獲得一個可重新排列的列表,但我無法堅持新的安排。 我有一個功能組件,可以在其中獲取項目列表。 項目結構是這樣的:項目 [ {name, courseList}, {name, courseList}, ...]。

為了填充表格,我調用了 api 並使用 MapStateToProps 更新了 prop 變量。 這是一段代碼:

function CoursesPage({
  student,
  studentCourses,
  loadStudentCourses,
  updateCoursesOrder,
  ...props
}) {
  useEffect(() => {
    if (studentCourses.length === 0) {
      loadStudentCourses(student.id).catch((error) => {
        alert("Loading student courses failed" + error);
      });
    }
  }, []);
...
}

這是 mapStateToProps function:

function mapStateToProps(state) {
  return {
    student: state.student,
    studentCourses: state.studentCourses,
  };
}

這一點工作正常,一切都出現了。 問題是當我嘗試重新排列並將其保存在 onSortEnd function 中時:

  function onSortEnd({ oldIndex, newIndex, collection }) {
    const newCollections = [...studentCourses];

    newCollections[collection].courseList = arrayMove(
      newCollections[collection].courseList,
      oldIndex,
      newIndex
    );

    updateCoursesOrder(newCollections);
  }

newCollection 被正確填充和修改,我正在調用 updateCoursesOrder 並正確排列項目。 function 是一個調用調度的動作。

export function updateCoursesOrder(courseList) {
  return function (dispatch) {
    dispatch(setNewCourseOrderSuccess(courseList));
  };
}

export function setNewCourseOrderSuccess(studentCourses) {
  return { type: types.SET_NEW_COURSE_ORDER, studentCourses };
}

使用調試器,我可以看到代碼運行良好,直到從 setNewCourseOrderSuccess() 調度返回。

這應該 go 到減速器,但會引發錯誤:未捕獲的不變違規:在調度之間檢測到 state 突變。

這是減速器的樣子:

export default function courseReducer(
  state = initialState.studentCourses,
  action
) {
  switch (action.type) {
    case type.LOAD_STUDENT_COURSES_SUCCESS:
      return action.studentCourses;
    case type.SET_NEW_COURSE_ORDER:
      return {
        ...state,
        studentCourses: action.payload,
      };
    default:
      return state;
  }
}

我該如何解決這個問題? 非常感謝!

有了這個:

const newCollections = [...studentCourses];

newCollections[collection].courseList =

雖然newCollections是一個新數組,但它只是studentCourses的淺拷貝; 數組項不是克隆,它們是對 state 中當前對象的引用。 因此,分配給這些對象之一的courseList屬性正在改變 state。

替換索引處的 object 而不是對其進行變異:

function onSortEnd({ oldIndex, newIndex, collection }) {
    updateCoursesOrder(studentCourses.map((item, i) => i !== collection ? item : ({
        ...item,
        courseList: arrayMove(item.courseList, oldIndex, newIndex)
    })));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM