当我运行此应用程序时,它的工作原理是NaN作为平均值和正值,而不是0或任何数值。如果单击按钮,我将获得准确的值。应用程序正在运行,但是当我重新启动应用程序时,我不知道如何删除此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 :(得分:4)
0/0
根本没有合理的解释,因此其NaN
。
答案 1 :(得分:2)
这里的问题是,在初始化期间,您所有的状态值均为0
,因此,当您第一次执行(good-bad)/(good + neutral + bad)
时,它的值为0/0
并除以{{1} }返回0
。
还请注意,对于像您这样的计数器,如果需要增加当前状态,则最好使用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)]
}
答案 2 :(得分:0)
我认为这可能是因为您试图除以0。如果将好,坏或中性值之一更改为1,则会开始显示数字。