【发布时间】:2020-08-15 22:54:46
【问题描述】:
我正在构建一个反应应用程序,它可以解决数独问题并可视化解决算法。
我正在尝试将类组件转换为功能组件,但不确定如何使状态更改生效。
有问题的代码是:
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 loop - 用
useEffect包裹useState(即useEffect(() => setBoard(board), [board]))。这没有编译,得到错误React Hook "useEffect" may be executed more than once... - 也查看了
useReducer,但有read it doesn't work well withasync
我的问题是:
- 这甚至可以转换为功能组件吗?
- 如果是,我应该使用什么钩子?是否需要重新设计我的
solve()函数? - 是否最好将其从类组件转换为函数组件?
【问题讨论】:
-
嘿,你试过
useAsyncEffect而不是useEffect吗?每当我有这样的异步钩子时,我都会使用这个 npm 包npm link
标签: reactjs react-hooks react-component react-functional-component use-state