使用react挂钩查找总数和打印平均值



在点击保存期间,我在控制台中一无所获。我想找到所有值的total,然后计算average

此处添加了演示:https://codesandbox.io/s/sad-pike-ljnfk?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [rating, setRating] = useState({
shooting: "",
dribbling: "",
ballcontrol: "",
sprinting: "",
fitness: ""
});
const [total, setTotal] = useState(0);
const onChange = e => {
e.persist();
//setRating({ ...rating, [e.target.name]: e.target.value });
const ratingValues = {
...rating,
[e.target.name]: e.target.value
};
setRating(ratingValues);
calculateAvgRating(ratingValues);
};
const calculateAvgRating = ratingValues => {
const {
shooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
parseInt(shooting) +
parseInt(dribbling) +
parseInt(ballcontrol) +
parseInt(sprinting) +
parseInt(fitness);
const finalAvg = newTotal / 5;
setTotal(finalAvg);
console.log("GGGGG:" + total);
};
return (
<div className="App">
<div className="row">
<div className="soccerFeatures">
<label>Shooting:</label>
<input name="shooting" onChange={e => setRating(e.target.value)} />
</div>
<div className="soccerFeatures">
<label>Dribbling:</label>
<input name="dribbling" onChange={e => setRating(e.target.value)} />
</div>
<div className="soccerFeatures">
<label>Ball Control:</label>
<input name="ballcontrol" onChange={e => setRating(e.target.value)} />
</div>
<div className="soccerFeatures">
<label>Sprinting:</label>
<input name="sprinting" onChange={e => setRating(e.target.value)} />
</div>
<div className="soccerFeatures">
<label>Fitness:</label>
<input name="fitness" onChange={e => setRating(e.target.value)} />
</div>
<button type="submit" className="submitButton" onClick={onChange}>
Save
</button>
</div>
</div>
);
}

使用Number而不是parseInt,因为Number('')产生0。此外,控制台在设置后立即记录total将不起作用,它将只记录当前渲染周期的值,而不是排队等待状态更新的值。相反,您可以只记录正在更新状态的值。

const calculateAvgRating = ratingValues => {
const {
shooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
Number(shooting) +
Number(dribbling) +
Number(ballcontrol) +
Number(sprinting) +
Number(fitness);
const finalAvg = newTotal / 5;
setTotal(finalAvg);
console.log("GGGGG:" + finalAvg);
};

注意,从技术上讲,将日志作为副作用更正确,例如使用useEffect挂钩。将total的日志记录移动到一个效果。这将在总值更新的任何时候记录。

useEffect(() => {
console.log("GGGGG:" + total);
}, [total]);

https://codesandbox.io/s/suspicious-booth-e9n44?file=/src/App.js

我添加了init值并修复了一些句柄,请查看:D

相关内容

  • 没有找到相关文章

最新更新