【问题标题】:Why my array getting appended instead of clearing and Adding new data为什么我的数组被追加而不是清除和添加新数据
【发布时间】:2021-05-04 21:04:05
【问题描述】:

我正在尝试实现一种方法,每次单击“创建新数组”按钮时,数组步骤都会填充新数据,但不是那样,而是数据被追加而不是更新。

这是我的状态:

const [arr , setArray] = useState(createArray())
const [steps , setSteps] = useState([]);
const [selectedAlgorithm , setSelectedAlgorithm] = useState ();

这是我创建新数组的函数:

const handleCreateNewData = ()=>{
    let newarr = createArray();
    setArray ([]);
    
    setArray([...newarr]);
    setSteps ([]);
    setTimeout(()=>{
        if ( algorithms[selectedAlgorithm] !== undefined){
            algorithms[selectedAlgorithm](arr, steps , setSteps);
            console.log('running')
        }

    },2000)
   
}

这是我的冒泡排序算法:

export const BubbleSort = (array , steps ,setSteps) =>{
let funarray = new Array();
funarray = [...array] ;
for (let i = 0 ; i < funarray.length-1 ; i++){
    for(let j = 0 ; j < funarray.length-1 ; j++){
        if(funarray[j]>funarray[j+1]){
            [funarray[j],funarray[j+1]] = [funarray[j+1],funarray[j]]
            setSteps([...steps, funarray])
            steps.push(funarray.slice());
            console.log('Working')
        }
    }
}


return funarray;
 } 

应该做的是每次我点击创建新数组时,它应该生成一组新数组,而不是创建新数组,它只是在旧步骤中附加新数组。

【问题讨论】:

    标签: arrays reactjs algorithm bubble-sort react-state


    【解决方案1】:

    您可以创建一个临时数组来保存步骤,然后在循环完成后调用 setSteps:

    const BubbleSort = (array, steps, setSteps) => {
      let funarray = [];
      funarray = [...array];
      let temp = [];
      for (let i = 0; i < funarray.length - 1; i++) {
        for (let j = 0; j < funarray.length - 1; j++) {
          if (funarray[j] > funarray[j + 1]) {
            [funarray[j], funarray[j + 1]] = [funarray[j + 1], funarray[j]];
            temp.push(funarray)
          }
        }
      }
      setSteps(temp);
    
      return funarray;
    };
    

    示例:https://codesandbox.io/s/cool-wind-ijj7z?file=/src/App.js

    【讨论】:

    • 实际上,每次交换发生时,我都会尝试将新数组推送到步骤,因此,如果我这样做,它将给我的应用程序的基本功能带来问题。
    猜你喜欢
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多