我正在构建一个可解决数独板并可视化解决算法的React应用。
我正在尝试将类组件转换为功能组件,但是不确定如何使状态更改生效。
有问题的代码是:
async solve() {
await this.sleep(0);
const board = this.state.board;
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (board[row][col] !== 0) {
// can't change filled cells
continue;
}
// try 1 to 9 for the empty cell
for (let num = 1; num <= 9; num++) {
if (App.isValidMove(board, row, col, num)) {
// valid move, try it
board[row][col] = num;
this.setState({ board: board });
if (await this.solve()) {
return true;
} else {
// didn't solve with this move, backtrack
board[row][col] = 0;
this.setState({ board: board });
}
}
}
// nothing worked for empty cell, must have deprived boards solution with a previous move
return false;
}
}
// all cells filled
return true;
}
(Full code here和app is hosted here)
[这里我需要async
,所以我可以使用sleep()
可视化该算法。每当板子发生变化时,我都使用this.setState({ board: board });
触发重新渲染。
[尝试转换为功能组件时,我尝试了:
useState
钩子,我使用了const [board, setBoard] = useState(initialBoard);
并将this.setState
调用替换为setBoard(board)
。这没有用,因为该钩子是called in a loopuseState
(即useEffect
)包装useEffect(() => setBoard(board), [board])
。此未编译,出现错误React Hook "useEffect" may be executed more than once...
useReducer
但有read it doesn't work well with async
我的问题是:
async
函数?尝试solve()
钩useAsyncEffect
我希望它是标准React库的一部分