Vuex突变未更新状态

问题描述

我这里有点问题。直到刷新页面,我的突变才会更新状态。

操作

async restoreDeletedCours({ commit },cours) {
  let response = await Axios.post("/dashboard/school/cours/restoreDeletedCours",cours);
  let crs = response.data.data;
  if (response.status == 200 || response.status == 201) { 
    commit("REMOVE_COURS_FROM_DELETED_LIST",crs);
    commit("RESTORE_SCHOOL_DELETED_COURS",crs);
    return response.data;
  }
}

突变

REMOVE_COURS_FROM_DELETED_LIST(state,crs) {
   // Let's remove the restored Item from deleted List
   let removeFromDeletedList = state.deletedCourses.filter(c => c.id != crs.id);
   state.deletedCourses = removeFromDeletedList;
}

enter image description here

解决方法

问题是reactivity of the Mutation,改变数组的方式不是被动的,处理好后的数组是被动的,无论它们是组件的局部变量还是它们的Vuex状态都具有相同的行为:>

此分配对数组不起作用

state.deletedCourses = removeFromDeletedList;

尝试以下方法:

突变:

REMOVE_COURS_FROM_DELETED_LIST(state,crs) {

  //We get the indexes that we have to remove

  let indexArr = state.reduce(function(acc,val,index) {
    if (val != crs.id) {
      acc.push(index);
    }
    return acc;
  },[]);

  //We iterate this indexes and mutate properly the state array so changes are reactive

  indexArr.forEach( i => state.deletedCourses.splice(i,1) );

}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...