React Hook,用于通过异步递归函数更新的重新渲染状态

问题描述 投票:0回答:1

我正在构建一个可解决数独板并可视化解决算法的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 hereapp is hosted here

[这里我需要async,所以我可以使用sleep()可视化该算法。每当板子发生变化时,我都使用this.setState({ board: board });触发重新渲染。


[尝试转换为功能组件时,我尝试了:

  • useState钩子,我使用了const [board, setBoard] = useState(initialBoard);并将this.setState调用替换为setBoard(board)。这没有用,因为该钩子是called in a loop
  • useState(即useEffect)包装useEffect(() => setBoard(board), [board])。此未编译,出现错误React Hook "useEffect" may be executed more than once...
  • 也查看了useReducer但有read it doesn't work well with async

我的问题是:

  • 甚至有可能转换为功能组件吗?
  • 如果是,我应该使用哪个挂钩,是否需要重新设计async函数?
  • 将其从类组件转换为功能组件最好吗?
reactjs react-hooks react-component react-functional-component use-state
1个回答
0
投票

尝试solve()useAsyncEffect

我希望它是标准React库的一部分

© www.soinside.com 2019 - 2024. All rights reserved.