首页 > 解决方案 > 为什么我得到 NaN ?应用程序似乎可以工作,但起点是 NaN。我该如何解决这个问题?

问题描述

当我运行这个应用程序时,它的工作但不是 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 并将值设置为零。仍在开发这个应用程序,所以我没有在组件内部制作任何组件,所以它有点乱。

谢谢转发。

标签: reactjsjsxincrementnan

解决方案


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


推荐阅读