javascript - 如何在React中一个一个地循环遍历div标签内的数组元素
问题描述
所以,我有大量的二维数组。每个二维数组基本上是我的回溯算法找到数独解决方案的一个步骤。我想找到一种在表格中显示每个步骤的方法。我已经有了css和所有这些。我只需要一种方法来循环完成所有步骤,一个接一个,在同一张表中。有点像那些解释回溯是如何发生的动画。
有没有办法我可以做到这一点?我认为您不需要任何代码,但我会在控制台中粘贴 2d 数组数组的图片 [我猜您可以将其称为 3d 数组]。
PS:另外,直接使用 document.getElementById('output').innerHTML 不起作用,无论是在解决数独本身的函数中,还是在 useEffect Hook 中的另一个 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)
}
}, [])
解决方案
这个答案实际上是由用户@TJ Crowder 给我的。他回答了这个被简化为普通数组的问题,here。
假设这是一个功能组件,您需要让组件在设置下一个状态之前呈现每个状态。否则,所有状态更新都会被批处理在一起,并且组件只有在它们全部完成后才会再次呈现。
例如:
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>;
}
推荐阅读
- reactjs - 开玩笑 Create-React-App 中的意外令牌
- c# - 如何在 Unity 2D 中的 if 语句中检查碰撞
- linux - Tomcat 9 在终端 [ubuntu 18.04] 上启动,但未在浏览器中加载
- swift - SwiftUI 列出空状态视图/修改器
- python - Python中的张量流eval()函数
- node.js - Chart.js 误读标签和轴的数组
- javascript - 获取网页上用户选择的文本中包含的元素列表
- java - Java 中 DTO 对象的替代方案
- java - 超过 64k 方法非 Multidex 调试解决方案
- python - 复制命令阻止 postgres 中的其他会话