【问题标题】:How do you create a function progress bar in react?你如何在反应中创建一个功能进度条?
【发布时间】:2021-10-07 15:55:36
【问题描述】:

我有一个反应按钮,当我按下它时,它会模拟输入的轮盘游戏数量。这是为了看看您可以期望从赌场提供的轮盘赌红利中赚回多少。无论如何,当模拟次数设置为像 1000000 次模拟这样的大数字时,需要 10+ 秒才能完成并显示结果。我想添加一个进度条,因此每完成 1% 的模拟,进度条就会更新为另外 1% 的完成。这将使用户更好地了解模拟需要多长时间,并让他们知道计算机没有崩溃。

这里是轮盘赌功能,以备不时之需...

const SimulateEuroRoulette = (starting_balance, wagering, bet_size, simulations) => {
    let results = []
    for(let i = 0; i < simulations; i++){
        let balance = starting_balance
        let wagering_complete = 0
        let bust_out = false
        
        while(bet_size <= balance && wagering_complete < wagering){
            const random_int = random.int(0, 36)
            balance -= bet_size
            if(random_int > 18){
                balance += bet_size * 2
            }

            wagering_complete += bet_size
        }

        if(balance < bet_size && wagering > wagering_complete){ bust_out = true }

        results.push({ balance, wagering_complete, bust_out })
    }

    let bust_out_count = 0
    let balance_total = 0
    let wagering_total = 0
    let simulated = 0
    for(let i = 0; i < simulations; i++){
        if(results[i].bust_out){ bust_out_count++ }
        if(!results[i].bust_out){
            balance_total += results[i].balance
        }
        wagering_total += results[i].wagering_complete
        simulated++
    }

    return { ev: balance_total / simulations, average_wagered: wagering_total / simulations, bust_out_rate: ((bust_out_count / simulations) * 100), simulated }
}

【问题讨论】:

    标签: reactjs progress-bar


    【解决方案1】:

    您需要重构您的函数,以便它在迭代时更新状态变量(可能使用useReducer,因为您想同时更新多个状态变量)。您的变量之一是模拟完成的百分比。这将是您随后将与进度条的值相关联的变量。

    <label for="progress">progress:</label>
    <progress id="progress" value={state.progress} max="100"> {state.progress}% </progress>
    

    在您的reducer 中,您可能希望逻辑仅在您的百分比为整数或四舍五入时更新progress。不要让你的 SimulateEuroRoulette 方法依赖于状态,只需让它 dispatch 需要你的状态更新。您可能希望函数定义在您的组件之外,因此您需要传入 dispatch 来调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2022-01-17
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      相关资源
      最近更新 更多