为什么我会得到 NaN?应用程序似乎有效,但起点是 NaN.我该如何解决这个问题?



当我运行这个applicatio.n时,它可以工作,但不是0或其他任何东西,而是得到NaN作为平均值和正值。如果我点击按钮,我会得到精确的值。应用程序正在运行,但当我再次启动应用程序时我不知道如何删除此 NaN

import React, { useState } from 'react';
import { Table } from 'reactstrap';
import './App.css';

const App = () => {
const [good, setGood] = useState(0)
const [neutral, setNeutral] = useState(0)
const [bad, setBad] = useState(0)
const handleGood = () => {
setGood(good + 1)
}
const handleNeutral = () => {
setNeutral(neutral + 1)
}
const handleBad = () => {
setBad(bad + 1)
}
const average =  (((good-bad)/(good + neutral + bad))*100).toFixed(1);
const positive = ((good / (good + neutral + bad))*100).toFixed(1);
if (average < 0) {
alert('Your score is lower then 0')
}
return (
<div className="container mt-5">
<h1 className="text-center pb-2">Stankove ocene</h1>
<Table bordered hover>
<thead>
<tr className="text-center">
<th>#</th>
<th><button className="btn btn-success" onClick={handleGood}>Good</button></th>
<th> <button className="btn btn-primary" onClick={handleNeutral}>Neutral</button></th>
<th><button className="btn btn-danger" onClick={handleBad}>Bad</button></th>
<th><h5>Overall Feedback</h5></th>
<th><h5>Average</h5></th>
<th><h5>Positive</h5></th>
</tr>
</thead>
<tbody>
<tr className="text-center">
<th scope="row">Feedback</th>
<td><p>{good}</p></td>
<td><p >{neutral}</p></td>
<td><p>{bad}</p></td>
<td><p>{good + neutral + bad}</p></td>
<td><p>{average}%</p></td>
<td><p>{positive}%</p></td>
</tr>
</tbody>
</Table>

</div>
)
}

export default App;

我没有任何错误,我只是不会摆脱 NaN 并将值设置为零。 仍在开发此应用程序,所以我还没有在组件内部制作任何组件,所以有点混乱。

谢谢转发。

0/0根本没有合理的解释,因此它的NaN

这里的问题是,在初始化期间,所有状态值都是0的,所以当你第一次(good-bad)/(good + neutral + bad)时,它的计算结果是0/00返回NaN

另请注意,对于像您这样的计数器,如果您需要递增当前状态,最好使用setState的功能形式,因为它将确保始终获取状态的最新值:

const handleGood = () => {
setGood(currentGood => currentGood + 1)
}

解决此问题的一种方法是检查您是否按0方法划分并默认返回0

const formatValue = (val) => (val * 100).toFixed(1);
// Return array of values, where 1st item is average and second is positive
const getValues = () => {
const divider = good + neutral + bad;
if (divider === 0) {
return ['0', '0'];
}
return [formatValue((good - bad) / divider), formatValue(good / divider)]
}

用法,数组解构:

const [avg, positive] = getValues(); 

我认为这可能是因为您试图除以 0。如果您将好、坏或中性值之一更改为 1,它将开始显示数字。

最新更新