如何在 React 中一个一个地循环遍历 div 标记内的数组元素

How do I cycle through the elements of an array inside of a div tag one by one in React

所以,我有一个 巨大的 二维数组。每个 2d 数组基本上是我的回溯算法寻找数独解决方案的一个步骤。我想找到一种在 table 中显示每个步骤的方法。我已经有了 css 等等。我只需要一种方法在同一个 table 中一个接一个地循环执行所有步骤。有点像那些解释回溯是如何发生的动画。

我有办法做到这一点吗?我认为您不需要任何代码,但我会在控制台中粘贴一张二维数组的图片 [我猜您可以将其称为 3d 数组]。

PS:另外,直接使用document.getElementById('output').innerHTML是行不通的,无论是在解决数独本身的函数中,还是在useEffect中的另一个for循环中勾.

这是我目前所掌握的。


function sleep(milliseconds) {
        const date = Date.now();
        let currentDate = null;
        do {
          currentDate = Date.now();
        } while (currentDate - date < milliseconds);
}

useEffect(()=>{
        results = solve(matrixx,n); //returns 3D array of format [[sudoku board],[sudoku board],[sudoku board]...], each sudoku board is a 2d array in which each element array is one row.
        console.log(results.length)
        var result = results.filter((i,idx) => results[idx-1] !== i) //Removes any duplicate sudoku boards right next to each other
        console.log(result)
        for(var k in result){
            document.getElementById('output').innerHTML = JSON.stringify(result[k]) //Tag with output is a div tag temporarily. I expected this code to fill the div tag with one sudoku board, wait for 10 milliseconds and then fill it with the next sudoku board in result. However, what really happens is wait for a long time and then fill the tag directly with the last sudoku board, which is also the solution to the sudoku problem. 
            sleep(10)
        }
    }, [])

这个答案其实是网友@T.J给我的。拥挤。他回答了这个简化为普通数组的问题,

假设这是一个功能组件,您需要让组件在设置下一个状态之前呈现每个状态。否则,所有状态更新都会一起批处理,并且组件只会在全部完成后再次呈现。

例如:

    function Example() {
        const [arr, setArr] = useState([1,2,3,4,5,6,7,8,9,0]);
        // Set up a timer on mount, remove it on dismount and when
        // we run out of values to show
        useEffect(() => {
            const handle = setInterval(() => {
                // Note useing the callback function, so `arr` isn't stale
                // in this callback
                setArr(a => {
                    if (a.length) {
                        // Update the array, dropping the first entry
                        return a.slice(1);
                    }
                    // No more entries, stop the timer
                    clearInterval(handle);
                    return a;
                });
            }, 500);
            return () => clearInterval(handle);
        }, []);
        return <div>{arr.join()}</div>;
    }