reactjs - React useReducer 中的问题
问题描述
我正在尝试在 ReactJs 中做 2048 游戏,并且我正在使用功能组件来保持简单。我下面的代码是如何工作的,当我按下向上键时,状态中的每个数据都会发生变化,并且状态是一个二维数组。我是功能组件的新手,我看到很多事情都失控了。
function reducer(state, action){
console.warn('INSIDE REDUCER')
switch (action.type){
case 'UP':
console.warn("UP");
return action.payload
}
}
function App() {
let [ boxes, dispatch ] = useReducer(reducer, [[2,4,2,4],[2,'',2,''],[8,16,2,2],['',2,2,'']])
let moveup = () =>{
//code that will change the state(boxes)
let tempboxes = boxes
tempboxes.map((each)=>{
//maps through each subarrays and change the values
})
console.log(boxes) //i was surprised as well as shocked here because i never changed the state(boxes) anywhere
dispatch({type: 'UP',payload:tempboxes}) //Note i called dispatch after console.log but am seeing the state update here.
}
// event handling function to get the arrow keys input
document.onkeydown = function(event) {
switch (event.keyCode) {
//other keys
case 38:
console.log('Up key pressed');
moveup();
break;
}}
return(
//jsx part)
}
export default App;
逻辑按预期工作正常,但在下图中你可以清楚地看到我的盒子状态正在更新,即使我没有改变它(因为它在调度之前)并且在调用调度之后它甚至没有调用减速器函数(没有得到内部减速器警告)。
这是我们在功能组件中使用函数的方式吗?它哪里出错了?