繁体   English   中英

如何使用挂钩在 function 中传递 state 的值

[英]How to pass value of state in a function in react using hooks

所以,我一直在做一个项目。 我想将 state 的值作为参数传递给函数,或者我的理解可能是错误的。 我创建了一个名为 resetArray 的 function。 我在其中创建随机值数组并设置数组的 state。 现在我希望将该数组作为参数传递给 mergeSort function 以对数组进行排序,但我认为我的方法不正确。

 import React from 'react' import { useEffect } from 'react'; import { useState } from 'react' import './Randomarray.css' export default function RandomArrayJanrator() { const [array, setArray] = useState([]); useEffect(() => { resetArray(); }, []) const resetArray = () => { const array = []; for (let i = 0; i < 310; i++) { //array.push(Math.abs(Math.floor(Math.random() * (1000 - 10) - 10))); array.push(randomIntFromInterval(5, 750)); setArray(array); } } function randomIntFromInterval(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } function mergeSort(array) //trying to pass state here as a perameter { if (array.length === 1) return array; const middle = Math.floor(array.length / 2); const firstHalf = mergeSort(array.slice(0, middle)); const secondHalf = mergeSort(array.slice(middle)); const sortedArray = []; let i = 0, j = 0; while (i < firstHalf.length && j < secondHalf.length) { if (firstHalf[i] < secondHalf[j]) { sortedArray.push(firstHalf[i++]) } else { sortedArray.push(secondHalf[j++]); } } while (i < firstHalf.length) sortedArray.push(firstHalf[i]); while (j < secondHalf.length) sortedArray.push(secondHalf[j]); return sortedArray; } return ( <> <div className='container'> {array.map((value, indx) => ( <div className='array-bar' key={indx} style={{ height: `${value}px`, color: '#fff', fontSize: '2px' }}>{value}</div> ))} </div> <button onClick={() => resetArray()}>Array Genrator</button> <button onClick={() => mergeSort()}>Merge Sort</button> </> ) }

运行合并排序时出错

在此处输入图像描述

在此处输入图像描述

首先,您的算法中存在导致无限循环的问题,此处:

 while (i < firstHalf.length) sortedArray.push(firstHalf[i]);
 while (j < secondHalf.length) sortedArray.push(secondHalf[j]);

你忘了增加ij

关于您的问题,我通过调用帮助器 function 的mergeSort function 解决了它,然后使用排序后的数组设置 state。 这是带有一些注释的代码:

import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import './Randomarray.css'

export default function RandomArrayJanrator() {
  const [array, setArray] = useState([]);

  useEffect(() => {
    resetArray();
  }, []);

  const resetArray = () => {
    const array = [];
    for (let i = 0; i < 310; i++) {
      array.push(randomIntFromInterval(5, 750));
    }
    // You can move this out of your loop
    setArray(array);
  };

  function randomIntFromInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

  // You can define a function that sort the array using merge sort
  // and then set the state
  function mergeSort() {
    const sorted = mergeSortHelper(array);
    setArray(sorted);
  }

  // This is an helper function that works correctly with recursion
  function mergeSortHelper(array) {
    if (array.length <= 1) return array;
    const middle = Math.floor(array.length / 2);
    const firstHalf = mergeSortHelper(array.slice(0, middle));
    const secondHalf = mergeSortHelper(array.slice(middle));

    const sortedArray = [];

    let i = 0,
      j = 0;

    while (i < firstHalf.length && j < secondHalf.length) {
      if (firstHalf[i] < secondHalf[j]) {
        sortedArray.push(firstHalf[i++]);
      } else {
        sortedArray.push(secondHalf[j++]);
      }
    }

    // You forgot to increment you counters here causing an infinite loop
    while (i < firstHalf.length) sortedArray.push(firstHalf[i++]);
    while (j < secondHalf.length) sortedArray.push(secondHalf[j++]);
    return sortedArray;
  }

  return (
    <>
      <div className="container">
        {array.map((value, indx) => (
          
          //removed the styles temporarely because i couldn't read results
          <div className="array-bar" key={indx}>
            {value}
          </div>
        ))}
      </div>
      <button onClick={() => resetArray()}>Array Genrator</button>

      <button onClick={() => mergeSort()}>Merge Sort</button>
    </>
  );
}

演示: https://stackblitz.com/edit/react-2ueaft?file=src%2FRandomArrayJanrator.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM