【发布时间】:2020-04-10 02:13:47
【问题描述】:
我想在其他状态更新后更新一个状态:
export default function App() {
const [diceNumber, setDiceNumber] = useState(0);
const [rolledValues, setRolledValues] = useState([
{ id: 1, total: 0 },
{ id: 2, total: 0 },
{ id: 3, total: 0 },
{ id: 4, total: 0 },
{ id: 5, total: 0 },
{ id: 6, total: 0 }
]);
const rollDice = async () => {
await startRolingSequence();
};
const startRolingSequence = () => {
return new Promise(resolve => {
for (let i = 0; i < 2500; i++) {
setTimeout(() => {
const num = Math.ceil(Math.random() * 6);
setDiceNumber(num);
}, (i *= 1.1));
}
setTimeout(resolve, 2600);
});
};
useEffect(()=>{
if(!diceNumber) return;
const valueIdx = rolledValues.findIndex(val => val.id === diceNumber);
const newValue = rolledValues[valueIdx];
const {total} = newValue;
newValue.total = total + 1;
setRolledValues([
...rolledValues.slice(0,valueIdx),
newValue,
...rolledValues.slice(valueIdx+1)
])
}, [diceNumber]);
return (
<div className="App">
<button onClick={rollDice}>Roll the dice</button>
<div> Dice Number: {diceNumber ? diceNumber : ''}</div>
</div>
);
}
这是sandbox
当用户掷骰子时,一对 setTimeouts 将改变状态值并最终解决。一旦解决,我想跟踪一组对象中的分数。
所以当我这样写它时,它可以工作,但 eslint 给我一个缺少依赖项的警告。但是当我放入依赖项时,useEffect 将在一个永远循环中结束。
如何在状态更新后实现状态更新而不会导致永远循环?
【问题讨论】:
-
它专门抱怨依赖rolledValues,你有没有尝试将它添加到依赖列表中?
-
当我添加它时,它会在每次更新时更新,这将导致永远循环,我用沙盒链接更新了问题
-
这就是依赖列表中缺少的依赖。您能否阐明为什么需要使用 useEffect 进行这些状态更新?你能改为在
rollDice中更新rolledValues吗? -
你是对的,这会起作用,但是,我忘记了一些重要的事情,我执行了一堆超时来模拟掷骰子。因此,我必须等到状态更新,直到我可以更新分数保持数组。
标签: reactjs react-hooks use-effect use-state