简体   繁体   English

如何计算反应钩子中 state 变化的百分比

[英]How to calculate percentage on state change in react hooks

i am having the below state我有以下 state

const [data,setData] = useState({maths:null,physics:null,chem:null,percentage:null})

and i was updating the state as我正在将 state 更新为

setData({...data,[e.target.name]:e.target.value})

and my fuction for calculating the percentage is我计算百分比的功能是

function percentage(data.maths,data.physics,data.chem){ 
     const per = ((data.maths+data.physics+data.chem)/100)*100
return per
}

my doubt is when to call this function(like useEffect or like normal) and store it in data.percentage please help me我的疑问是何时调用此函数(如 useEffect 或正常)并将其存储在 data.percentage 请帮助我

Try doing the function in useState as shown below and as mentioned pass the state as the array deps, so whenever any of the property in the state changes it will recalculate, which is your required output. Try doing the function in useState as shown below and as mentioned pass the state as the array deps, so whenever any of the property in the state changes it will recalculate, which is your required output.

or as Germa suggested you can skip the function itself and do it something like this或者正如 Germa 建议的那样,您可以跳过 function 本身并做这样的事情

const [avg, setAvg] = useState(0)

useEffect(() => {
    const {
        maths,
        physics,
        chem
    } = data
    const per = ((data.maths + data.physics + data.chem) / 100) * 100
    setState(per)
}, [data])

I have added the codesandbox based on the discussion, having it in diff state will be much more better way, or else when you pass the array deps it will keep on changing.我已经根据讨论添加了代码框,将其放在 diff state中会更好,否则当您传递数组 deps 时,它将不断变化。

function percentage(data){ const per = ((data.maths+data.physics+data.chem)/100)*100 return per }

Like so:像这样:

useEffect(() => {
    const { maths, physics, chem } = data;
    const percentage = ((maths + physics + chem) / 100) * 100;
    setData({ maths, physics, chem, percentage });
  }, [data]);

the useEffect will run every time data changes, and data.percentage will be recalculated. useEffect 将在每次数据更改时运行,并且 data.percentage 将重新计算。

First of all, percentage should be divided by 300 I guess.首先,我猜百分比应该除以 300。 The percentage was a part of the same data as your input field so it was causing infinite loop whenever we were setting percentage in useEffect .百分比是与您的输入字段相同的数据的一部分,因此每当我们在useEffect设置百分比时,它都会导致无限循环。 So, it's better to separate the percentage from the input data of subjects.因此,最好将百分比与受试者的输入数据分开。

Working Demo 工作演示

import { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState({ maths: 0, physics: 0, chem: 0 });
  const [percentage, setPercentage] = useState(0);

  const fields = [
    { name: "maths", value: data.maths },
    { name: "physics", value: data.physics },
    { name: "chem", value: data.chem }
  ];

  useEffect(() => {
    // Not sure but percentage should be divided 300 I guess
    const per = ((data.maths + data.physics + data.chem) / 300) * 100;
    setPercentage(per);
  }, [data]);

  const handleChange = (e) => {
    console.log(e.target.value);
    setData({
      ...data,
      [e.target.name]: parseInt(e.target.value)
    });
  };

  return (
    <div>
      <h1>Percentage: {percentage}</h1>
      {fields.map((field, idx) => (
        <input
          key={idx}
          placeholder={field.name}
          name={field.name}
          value={field.value}
          onChange={handleChange}
        />
      ))}
    </div>
  );
};

export default App;

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

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