简体   繁体   English

使用 React 更新二维数组并挂钩 useState 和 useEffect

[英]Update 2d array using React and hooks useState and useEffect

I'm trying to create easy bouncing ball game in 2d array with React hooks.我正在尝试使用 React hooks 在 2d 数组中创建简单的弹跳球游戏。 I have a problem to solve:我有一个问题要解决:

When the ball hits the green field , it should change the vector to random and change its value in the array from "Y" to "0" .当球击中绿色区域时,它应该将向量更改为随机并将其在数组中的值从 "Y" 更改为 "0" It changes direction, but the green space does not disappear from the board.它改变了方向,但绿色空间并没有从板上消失。 It's still back after re-render.重新渲染后它仍然回来。

Here's a full code: https://stackblitz.com/edit/react-cvlqsp?file=src/App.js这是一个完整的代码: https ://stackblitz.com/edit/react-cvlqsp?file=src/App.js

Edit编辑

I found that the green box disappears, but each time the ball moves, it re-renders and it looks like it permanently.我发现绿色框消失了,但是每次球移动时,它都会重新渲染,并且看起来永远像它。 I can't help myself not to render the whole thing every time but only the ball movement.我忍不住每次都不渲染整个东西,而只渲染球的运动。 Should I use this in useEffect?我应该在 useEffect 中使用它吗? and how?如何?

Here's functions for random vector and value of array changes not working:这是用于随机向量和数组更改值的函数不起作用:

let random = () => {
    if (Math.random() < 0.5) {
      setVectorX((vectorX *= -1));
    } else {
      setVectorY((vectorY *= -1));
    }
  };

  let checkforYCollsion = () => {
    if (board[positionY][positionX] === 'Y') {
      random();
      board[positionY][positionX] = '0'
      
    }
  };

You need to update the state with the changed 2d array by calling setBoardToDisplay , not by assigning the value of board , since this will not trigger a re-render.您需要通过调用setBoardToDisplay来使用更改后的 2d 数组更新状态,而不是通过分配board的值,因为这不会触发重新渲染。 You can do this by utilising a callback function in setBoardToDisplay .您可以通过使用setBoardToDisplay中的回调函数来做到这一点。

setBoardToDisplay((prev) => {
  // make desired changes to prev and return it
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM