【问题标题】:for-loop in function call with state hooks - React带有状态钩子的函数调用中的for循环 - React
【发布时间】:2021-03-13 09:02:55
【问题描述】:

我希望我的函数掷出 5 个骰子并将它们存储在我的骰子状态中。

在最近的版本中,我只存储一个对象以供下次单击,但我使 for 循环一次生成 5 个骰子,我如何将前一个 dce 对象存储在 for 中以进行下一次迭代循环?

import './App.css';
import Subgroup from './Subgroup'
import React, {useState} from 'react'


function App() {

  const [numberRolls, setNumberRolls] = useState(3);
  const [dices, setDices] = useState([]);


  return (
    <div className="App">
        <Subgroup 
          numberRolls = {numberRolls}
          setNumberRolls = {setNumberRolls}
          dices = {dices} 
          setDices = {setDices}
        />
    </div>
  );
}

export default App;
import React from 'react'


const Subgroup = ({numberRolls, setNumberRolls, dices, setDices}) => {

    const rollTheDice =  () => {
        if(numberRolls > 0) {
            setNumberRolls(numberRolls - 1);

            for(let i = 0; i < 5; i++) {
                setDices([...dices,                 // i think sth should be different here????
                    {id: Math.random()*100, 
                     number: Math.ceil(Math.random()*6)-1, 
                     selected: false} 
                ])
            }
        }
        console.log(dices)
    }

    return (
        <div> 
            <button onClick={ rollTheDice }>blablabala </button>
        </div>
    )
}

export default Subgroup;

【问题讨论】:

    标签: javascript reactjs react-hooks state


    【解决方案1】:

    尝试将结果保存在数组中,然后设置状态,例如:

    const result = [];
    
    for(let i = 0; i < 5; i++) {
      result.push({
        id: Math.random() * 100, 
        number: Math.ceil(Math.random() * 6) -1, 
        selected: false
      });
    }
      
    setDices(prev => [...prev, ...result]);
    

    【讨论】:

    • 哦,哇,没那么难,谢谢!
    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2021-06-21
    • 2020-06-09
    • 2021-11-27
    相关资源
    最近更新 更多