Javascript 在React中达到新状态(挂钩)
我有一个小的Tic-tac-toe游戏,一切都很好,除了我正在努力寻找代码中的finish函数。让我给你看Javascript 在React中达到新状态(挂钩),javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我有一个小的Tic-tac-toe游戏,一切都很好,除了我正在努力寻找代码中的finish函数。让我给你看 import React, { useState } from "react"; import { isGameOver } from "../Helper/helper"; import Square from "./Square"; const Board: React.FC = () => { const [s
import React, { useState } from "react";
import { isGameOver } from "../Helper/helper";
import Square from "./Square";
const Board: React.FC = () => {
const [squares, setSquares] = useState(new Array(9).fill(""));
const [activePlayer, setActivePlayer] = useState("Player 1");
const [winner, setWinner] = useState<any>();
const clickSquare = (id: number): void => {
if (!squares[id]) {
if (activePlayer === "Player 1") {
setActivePlayer("Player 2");
} else {
setActivePlayer("Player 1");
}
}
setSquares((prevSquares) => {
return prevSquares.map((square, i) => {
if (i === id && !square) {
square = activePlayer === "Player 1" ? "X" : "O";
}
return square;
});
});
};
return (
<div className="board">
<div className="game-field">
{squares.map((square, i) => {
return (
<Square clickSquare={clickSquare} square={square} key={i} i={i} />
);
})}
</div>
<p
style={{
marginRight: activePlayer === "Player 1" ? "250px" : "-250px",
}}
>
{activePlayer + "'s turn"}
</p>
<p> </p>
</div>
);
};
export default Board;
从“React”导入React,{useState};
从“./Helper/Helper”导入{isGameOver};
从“/Square”导入正方形;
const Board:React.FC=()=>{
const[squares,setSquares]=useState(新数组(9).fill(“”);
const[activePlayer,setActivePlayer]=useState(“播放器1”);
const[winner,setWinner]=useState();
常量clickSquare=(id:number):void=>{
如果(!squares[id]){
如果(activePlayer==“播放器1”){
setActivePlayer(“播放器2”);
}否则{
setActivePlayer(“播放器1”);
}
}
固定方格((前置方格)=>{
返回prevSquares.map((Squares,i)=>{
if(i==id&&!square){
square=activePlayer==“Player 1”?“X”:“O”;
}
返回广场;
});
});
};
返回(
{squares.map((squares,i)=>{
返回(
);
})}
{activePlayer+“'该轮到你了”}
);
};
导出默认板;
这基本上就是整个游戏,我在另一个类似这样的文件中有一个结束函数
export const isGameOver = (squares: String[]) => {
const won = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < won.length; i++) {
const [x, y, z] = won[i];
if (squares[x] && squares[x] === squares[y] && squares[y] === squares[z]) {
return squares[x];
}
}
return null;
};
export const isGameOver=(方块:String[])=>{
常元=[
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for(设i=0;i
finishing函数也工作得很好,但是由于useState是异步工作的,我知道这一点,所以我很难把它放在哪里。如果我将click函数放入其中,它将无法对新状态做出反应,只能对之前的状态做出反应。如果我用just-If语句放在外面,它会说太多渲染,因为我设置了赢家等等。。我的意思是我也想停止游戏,停止点击事件等等。。找不到实现此功能的方法。似乎需要
useffect
。基本上,检查游戏是否结束,每次点击一个方块:
useEffect(() => {
if(squares){
if(isGameOver(squares)){
setSquares(null)
/* Do other stuff */
}
}
}, [squares])
通过将
squares
传递给依赖项数组,您告诉react希望每次squares
状态变量更改时都运行此useffect
。你可以在这里我不知道为什么我没有考虑使用效果。。谢谢,非常感谢。没问题,祝您愉快