我正在嘗試做一個戰艦游戲,這是我生成計算機船的邏輯:
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/exhaustive-deps
當我將 newLayout 變數添加到依賴項陣列時,應用程式會因 useEffect 多次重新渲染而崩潰。我該如何解決這個錯誤?也許我使用了錯誤的 useEffect 方式。
uj5u.com熱心網友回復:
您的效果取決于狀態變數的先前值,因此您可以執行以下操作,而不是將其作為依賴項:
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 檔案 中了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/333480.html
標籤:javascript 反应 使用效果
