gpt4 book ai didi

javascript - 我的 React Typescript 获胜百分比计数器中出现逻辑 NaN 错误

转载 作者:行者123 更新时间:2023-12-02 21:00:10 24 4
gpt4 key购买 nike

我正在制作一个简单的 Typescript 计数器来跟踪我玩的 Legends of Runeterra 游戏的获胜百分比。我不明白为什么当我增加胜利或失败时我会得到 NaN 作为我的获胜百分比。逻辑看起来不错(显然你现在不能递减,这是以后的问题),我现在只想专注于修复 NaN 错误。

这是我的计数器组件:

import React, { useState } from 'react'

// add a ? after the type name if you want any one of these to be optional, ex: wins?
const Counter: React.FC<{
initialGamesPlayed: number
initialWins: number
initialLosses: number
initialWinPercentage: number
initialDeckName: string
}> = ({
initialDeckName,
initialWinPercentage,
initialWins,
initialLosses,
initialGamesPlayed,
}) => {
const [deckName, setDeckName] = useState(initialDeckName)
const [wins, setWins] = useState(initialWins)
const [losses, setLosses] = useState(initialLosses)
const [totalGames, setTotalGames] = useState(initialGamesPlayed)
const [winPercentage, setWinPercentage] = useState(initialWinPercentage)

const incrementWins = () => {
setWins(wins + 1)
winPercentageCalc()
console.log(winPercentage)
}
const decrementWins = () => {
if (wins > 0) setWins(wins - 1)
winPercentageCalc()
}
const incrementLosses = () => {
setLosses(losses + 1)
winPercentageCalc()
console.log(winPercentage)
}
const decrementLosses = () => {
if (losses > 0) setLosses(losses - 1)
winPercentageCalc()
}
const winPercentageCalc = () => {
setTotalGames(wins + losses)
setWinPercentage((wins / totalGames) * 100)
}

return (
<div>
<p>Deck Name: </p>
<p>wins: {wins} </p>
<button onClick={incrementWins}>+</button>
<button onClick={decrementWins}>-</button>
<p>losses: {losses}</p>
<button onClick={incrementLosses}>+</button>
<button onClick={decrementLosses}>-</button>
<p>Win Percentage: {winPercentage} % </p>
</div>
)
}

export default Counter

感谢您的浏览!

最佳答案

setWins、setLosses、setTotalGames 和 setWinPercentage 都是异步函数。因此,第一次调用 winPercentageCalc 时,会发生以下情况:

const winPercentageCalc = () => {
setTotalGames(wins + losses) // This is asynchronous, so...
setWinPercentage((wins / totalGames) * 100) // totalGames = 0 => NaN
}

当您除以总游戏数时,总游戏数尚未更新,因此除以 0 会得到 NaN(非数字)结果

关于javascript - 我的 React Typescript 获胜百分比计数器中出现逻辑 NaN 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61375293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com