如何根据对状态数组变量的更改在 React 中重新渲染

问题描述

我正在尝试构建一个类似于以下内容的排序可视化工具:https://clementmihailescu.github.io/Sorting-Visualizer/ 使用 React。

为了在合并排序算法中的每一步处理更新画布,我尝试使用状态变量 yHeights(对应于每行的高度,进行排序)并在每次调用期间更新此变量的状态归并排序()。

但是,我遇到了一个无限循环,我相信是因为我没有保持 render() 方法“纯” - 比如,我在渲染方法期间更新状态。

如何重构此代码以在每次调用 mergesort() 期间正确更新画布绘图?我想我可以使用 getDerivedStateFromProps 来做到这一点,但我很难理解和实施使用 documentation

代码

//App.js
import logo from './logo.svg';
import './App.css';
import Controls from './Controls';
import Canvas from './Canvas';
import {useState} from 'react'

var xPositions = []

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}


function App() {

  const [yHeights,setyHeights] = useState([])

  function merge(left,right) {
    let sortedArr = []; // the sorted elements will go here
  
    while (left.length && right.length) {
      // insert the smallest element to the sortedArr
      if (left[0] < right[0]) {
        sortedArr.push(left.shift());
      } else {
        sortedArr.push(right.shift());
      }
    }
  
    // use spread operator and create a new array,combining the three arrays
    return [...sortedArr,...left,...right];
  }

  function mergeSort(arr) {
    setyHeights([arr])
    const half = arr.length / 2;
  
    // the base case is array length <=1
    if (arr.length <= 1) {
      return arr;
    }
  
    const left = arr.splice(0,half); // the first half of the array
    const right = arr;
    return merge(mergeSort(left),mergeSort(right));
  }

  const draw = context => {

  var arrHeights = []
  
  context.fillStyle = "rgb(0,0)";
  for (var i = 0; i < 100; i+=1) {
    const height = getRandomInt(500) 
    context.fillRect(i * 10,10,height);
    xPositions.push(i*10);
    arrHeights.push(height)
  }

  setyHeights(arrHeights);

  console.log(yHeights)

};

  return (
    <div className="App">
      <Controls />
      <Canvas draw={draw} numLines={100} />
    </div>
  );
}

export default App;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)