[英]React hooks, set return value of a function to state causes infinite loop
[英]for-loop in function call with state hooks - React
我希望我的 function 掷出 5 个骰子并将它们存储在我的骰子 state 中。
在最近的版本中,我只存储一个 object 以供下次单击,但我使 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;
尝试将结果保存在数组中,然后设置 state,类似于:
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.