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

Why I`m getting NaN ? Application seems to work but starting point is NaN. How can I solve this?

当我 运行 这个 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/0 并除以 0 returns NaN.

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

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

解决此问题的一种方法是检查您是否按 0 方法和默认 return 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)]
}

用法,与array destructuring :

const [avg, positive] = getValues(); 

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