【发布时间】:2021-01-29 13:10:21
【问题描述】:
下面是渲染任务数组的任务组件。
export function Task() {
const tasks = useSelector((state) => state.tasks.taskArray);
function handleOnDragEnd(result) {
if (!result.destination) return;
let items = [...tasks]; // also tried with tasks.slice() to obtain a deep copy
let i = result.source.index;
let direction = result.destination.index > result.source.index;
// direction true means moving right & swapping
while (i != result.destination.index) {
if (direction) {
let tempGlobalKey = items[i].globalKey;
items[i].globalKey = items[i + 1].globalKey; // <<< here
items[i + 1].globalKey = tempGlobalKey;
i++;
} else {
let tempGlobalKey = items[i].globalKey;
items[i].globalKey = items[i - 1].globalKey; // <<< here
items[i - 1].globalKey = tempGlobalKey;
i--;
}
}
dispatch(updateOrder(items));
}
.
..
... so on
在 taskSlice 中,updateOrder reducer 如下 // 使用 redux-toolkit 因此下面直接改变状态
export const tasksSlice = createSlice({
name: "tasks",
initialState: {
taskArray: [],
meta: {
globalKey: 0,
completedTaskStartIndex: -1,
},
},
reducers: {
updateOrder: (tasks, { payload }) => {
tasks.taskArray = payload;
},
}
......so on
当拖动结束并运行处理拖动结束时,错误出现在代码中标记的行上。错误信息是
TypeError: Cannot assign to read only property 'globalKey' of object '#<Object>'
handleOnDragEnd
src/containers/tasks/index.js:60
57 | i++;
58 | } else {
59 | let tempGlobalKey = items[i].globalKey;
> 60 | items[i].globalKey = items[i - 1].globalKey;
| ^ 61 | items[i - 1].globalKey = tempGlobalKey;
62 | i--;
63 | }
我知道状态不能直接改变,因此我正在更新数组的深层副本并将其设置为理想情况下应该工作的新状态。如果可以指出问题或者是否有其他方法可以实现这一点,我将不胜感激。
谢谢。
【问题讨论】:
标签: javascript arrays reactjs redux react-redux