我正在尝试做一款战舰游戏,这是我生成计算机舰船的逻辑:
const ComputerBoard = ({ COLUMNS, ROWS }) => {
const [layout, setLayout] = useState(new Array(ROWS * COLUMNS).fill('empty'));
const newLayout = [...layout];
useEffect(() => {
const checkIfShipFits = (isHorizontal, spaces, i) => {
let temp = 0;
const x = i % ROWS;
const y = Math.floor(i / COLUMNS);
for (let n = 0; n < spaces; n += 1) {
if (isHorizontal) {
if (x + spaces < COLUMNS && newLayout[i + n] !== 'ship') {
temp += 1;
}
}
if (!isHorizontal) {
if (y + spaces < ROWS && newLayout[i + COLUMNS * n] !== 'ship') {
temp += 1;
}
}
}
return temp === spaces;
};
const generateComputerLayout = () => {
const totalShips = computerShipsAvaibles;
const boardSize = ROWS * COLUMNS;
// Iterate over all types of ships
for (let j = 0; j < totalShips.length; j += 1) {
// Iterate over the amount of the specific ship
for (let k = 0; k < totalShips[j].amount; k += 1) {
let i = generateRandomIndex(boardSize);
const isHorizontal = generateRandomDirection();
while (!checkIfShipFits(isHorizontal, totalShips[j].spaces, i)) {
i = generateRandomIndex(boardSize);
}
for (let l = 0; l < totalShips[j].spaces; l += 1) {
if (isHorizontal) newLayout[i + l] = 'ship';
if (!isHorizontal) newLayout[i + COLUMNS * l] = 'ship';
}
}
}
setLayout(newLayout);
};
generateComputerLayout();
}, [COLUMNS, ROWS]);
Math.floor(Math.random() * (COLUMNS * ROWS));
return (
<div>
<h3>Computer</h3>
<div className='board'>
{layout.map((square, index) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={index}
className={`square ${square} computer`}
/>
))}
</div>
</div>
);
};
目前它正在工作,但在开发人员控制台中抛出警告:
React Hook useEffect缺少一个依赖项:'newLayout'。要么包含它,要么删除依赖数组react-hooks/精疲力竭-deps
当我将newLayout变量添加到依赖数组时,由于useEffect多次重新渲染,应用程序崩溃了。如何修复此错误?也许我用错了useEffect。
您的效果取决于状态变量的前一个值,因此您可以做以下操作,而不是将其作为依赖项:
const ComputerBoard = ({ COLUMNS, ROWS }) => {
const [layout, setLayout] = useState(new Array(ROWS * COLUMNS).fill('empty'));
useEffect(() => {
setLayout((previousLayout) => {
const newLayout = [...previousLayout];
...
return newLayout;
}
}, [COLUMNS, ROWS]);
...
当你希望下一个状态值依赖于前一个状态值时,你应该使用"功能更新",你可以在React文档中了解更多。