React:Slider onChangeEnd 后的无限函数调用循环

React: Infinite function call loop after Slider onChangeEnd

当我更改滑块的值时,它应该调用一个函数 onChangeEnd。但是,发生这种情况时,将在无限循环中调用 calculateEvent 函数。这将永远持续下去,即使之后我一直在移动我的滑块。为什么会这样?

var yearStart = 0;
var yearEnd = 50;
var years : number[] = [];
while(yearStart < yearEnd+1){
    years.push(yearStart++);
}
const xAxis : number[] = years;

const Savings = () => {

    const [initialSavings, setInitialSavings] = React.useState<string>("5000");
    const [monthlyDepo, setMonthlyDepo] = React.useState<string>("100");
    const [interestRate, setInterestRate] = React.useState<number>(2);
    const [yAxis, setYAxis] = React.useState<number[]>([]);

    const handleChange = useCallback((newValue) => {
        setInterestRate(newValue);
      }, []);

    const calculateEvent = useCallback((event : string, slider : number, option : number) => {
        switch(option) {
            case 1:
              setInitialSavings(event);
              break;
            case 2:
              setMonthlyDepo(event);
              break;
            case 3:
              setInterestRate(slider);
          }
        console.log("Calculate event called with slider value: ", interestRate);
        getProjection(initialSavings, monthlyDepo, interestRate).then((m) => {
            console.log(m);
            setYAxis(m);
        })
    }, [initialSavings, monthlyDepo, interestRate]);

    return(
    <DefaultLayout>
        <Container pt={6}>
            <VStack spacing={4}>
                <Heading as="h1">Interest Rate Calculator</Heading>
                <Heading as="h4">{initialSavings}, {monthlyDepo}, {interestRate}</Heading>
                <Input 
                    label="Initial Savings amount" 
                    name="Initial Savings" 
                    onInput={e => calculateEvent(e.currentTarget.value, 0, 1)} 
                    placeholder="5000"
                />
                <Input 
                    label="Monthly Deposit" 
                    name="Monthly Deposit" 
                    onInput={e => calculateEvent(e.currentTarget.value, 0, 2)} 
                    placeholder="100"
                />
                <Slider
                    label="Interest Rate"
                    name="Interest Rate"
                    value={interestRate}
                    min={1}
                    max={15}
                    step={1}
                    onChange={handleChange}
                    onChangeEnd={e => calculateEvent("", e, 3)} 
                    focusThumbOnChange={false}
                    role="group"
                    onFocus={(e) => {
                        e.preventDefault();
                    }}
                />
                <LineChart
                    title="Savings Over time"
                    xAxisData={xAxis}
                    yAxisData={yAxis}
                    xLabel="Years"
                    yLabel="Amount"
                />
            </VStack>
        </Container>
    </DefaultLayout>
    )
}

好的,这就是我的建议。

让我们将 calculateEvent 功能分解成单独的组件。

然后,让我们创建一个 useEffect 回调,只要我们的输入发生变化,它就会重新计算投影。我更愿意在渲染时执行此操作,但我们受困于效果,因为 getProjection returns 一个承诺。

现在,我明白你为什么要使用 onChangeEnd 事件了。 getProjection() 开销很大,因此您只想在用户完成选择值时调用它。

所以让我们把它分成两个状态。一种管理滑块值的状态。然后是第二个状态来保存实际的 interestRate 值。我们将等待更新 interestRate 值,直到 onChangeEnd 被调用。

此外,让我们确保通过在输入上放置值并使用 onChange 而不是 onInput 来控制这些输入。

var yearStart = 0;
var yearEnd = 50;
var years: number[] = [];
while (yearStart < yearEnd + 1) {
  years.push(yearStart++);
}
const xAxis: number[] = years;

const Savings = () => {
  const [initialSavings, setInitialSavings] = React.useState<string>('5000');
  const [monthlyDepo, setMonthlyDepo] = React.useState<string>('100');
  const [interestRate, setInterestRate] = React.useState<number>(2);
  const [interestRateSlider, setInterestRateSlider] = React.useState<number>(2);
  const [yAxis, setYAxis] = React.useState<number[]>([]);

  const handleSavingsChange = (e) => {
    setInitialSavings(e.target.value);
  }

  const handleMonthlyDepoChange = (e) => {
    setMonthlyDepo(e.target.value);
  }

  const handleInterestRateSliderChange = (value) => {
    setInterestRateSlider(value);
  };

  const handleInterestRateSliderChangeEnd = (value) => {
    setInterestRate(value)
  }

  useEffect(() => {
    getProjection(initialSavings, monthlyDepo, interestRate).then((m) => {
      setYAxis(m);
    });
  },[initialSavings, monthlyDepo, interestRate])

  return (
    <DefaultLayout>
      <Container pt={6}>
        <VStack spacing={4}>
          <Heading as="h1">Interest Rate Calculator</Heading>
          <Heading as="h4">
            {initialSavings}, {monthlyDepo}, {interestRate}
          </Heading>
          <Input
            label="Initial Savings amount"
            name="Initial Savings"
            value={initialSavings}
            onChange={handleSavingsChange}
            placeholder="5000"
          />
          <Input
            label="Monthly Deposit"
            name="Monthly Deposit"
            value={monthlyDepo}
            onChange={handleMonthlyDepoChange}
            placeholder="100"
          />
          <Slider
            label="Interest Rate"
            name="Interest Rate"
            value={interestRate}
            min={1}
            max={15}
            step={1}
            onChange={handleInterestRateSliderChange}
            onChangeEnd={handleInterestRateSliderChangeEnd}
            focusThumbOnChange={false}
            role="group"
            onFocus={(e) => {
              e.preventDefault();
            }}
          />
          <LineChart
            title="Savings Over time"
            xAxisData={xAxis}
            yAxisData={yAxis}
            xLabel="Years"
            yLabel="Amount"
          />
        </VStack>
      </Container>
    </DefaultLayout>
  );
};