我正在努力理解为什么使用 assign 设置 Context 并不总是有效。我有一个非常简单的应用程序,您可以在这里找到https://codesandbox.io/embed/y0xk1mo9x9
我有这样的背景:
{
selectedItem: 0, //Fake Value
nextSelectedItem: 0
}
由这些功能更新:
const decrementNextSelectItem = (context, event) => {
console.log("decrementNextSelectItem: " + context.nextSelectedItem);
assign({
nextSelectedItem:
context.nextSelectedItem > 0
? context.nextSelectedItem--
: context.nextSelectedItem
});
console.log("decrementNextSelectItem is now: " + context.nextSelectedItem);
};
const incrementNextSelectItem = (context, event) => {
console.log("incrementNextSelectItem: " + context.nextSelectedItem);
assign({
nextSelectedItem:
context.nextSelectedItem < 5
? context.nextSelectedItem++
: context.nextSelectedItem
});
console.log("incrementNextSelectItem is now: " + context.nextSelectedItem);
};
const updateCurrentSelectedItem = (context, event) => {
console.log(" updateCurrentSelectedItem: " + context.selectedItem);
assign({
selectedItem: context.nextSelectedItem
});
console.log(" updateCurrentSelectedItem is now: " + context.selectedItem);
};
decrementNextSelectItem
(与事件 UP_KEY 绑定 - 按向上箭头)和incrementNextSelectItem
(与事件 DOWN_KEY 绑定 - 按向下箭头)被正确调用:
incrementNextSelectItem: 0
incrementNextSelectItem is now: 1
DOWN KEY pressed
incrementNextSelectItem: 1
incrementNextSelectItem is now: 2
DOWN KEY pressed
incrementNextSelectItem: 2
incrementNextSelectItem is now: 3
DOWN KEY pressed
decrementNextSelectItem: 3
decrementNextSelectItem is now: 2
UP KEY pressed
但是updateCurrentSelectedItem
(与事件 OK_KEY 绑定 - 按 'o' 键)神秘地无法按预期工作:
updateCurrentSelectedItem: 0
updateCurrentSelectedItem is now: 0
OK KEY pressed
有什么理由吗?我快疯了。