You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
}, [count]); // 🚩 ... but specifying `count`as a dependency always resets the interval.
1431
+
}, [count]); // 🚩 ... но из-за того, что `count`в зависимостях, интервал постоянно перезапускается.
1432
1432
// ...
1433
1433
}
1434
1434
```
1435
1435
1436
-
Since`count`is a reactive value, it must be specified in the list ofdependencies. However, that causes the Effect to cleanup and setup again every time the `count`changes. This is not ideal.
1436
+
Т.к.`count`-- это реактивное значение, то оно должно быть указано в списке зависимостей. Но из-за этого эффекту приходится сбрасываться и запускаться заново каждый раз, когда `count`обновляется. Выглядит не идеально.
1437
1437
1438
-
To fix this, [pass the `c => c + 1` state updater](/reference/react/useState#updating-state-based-on-the-previous-state) to `setCount`:
1438
+
Можно сделать лучше, если передавать в `setCount` [функцию обновления состояния `c => c + 1`:](/reference/react/useState#updating-state-based-on-the-previous-state)
1439
1439
1440
1440
<Sandpack>
1441
1441
@@ -1447,10 +1447,10 @@ export default function Counter() {
1447
1447
1448
1448
useEffect(() => {
1449
1449
const intervalId = setInterval(() => {
1450
-
setCount(c => c + 1); // ✅ Pass a state updater
1450
+
setCount(c => c + 1); // ✅ Передаём функцию обновления
1451
1451
}, 1000);
1452
1452
return () => clearInterval(intervalId);
1453
-
}, []); // ✅ Now count is not a dependency
1453
+
}, []); // ✅ Теперь `count` нет в зависимостях.
1454
1454
1455
1455
return <h1>{count}</h1>;
1456
1456
}
@@ -1470,7 +1470,7 @@ body {
1470
1470
1471
1471
</Sandpack>
1472
1472
1473
-
Now that you're passing `c => c + 1` instead of `count + 1`, [your Effect no longer needs to depend on `count`.](/learn/removing-effect-dependencies#are-you-reading-some-state-to-calculate-the-next-state) As a result of this fix, it won't need to cleanup and setup the interval again every time the `count` changes.
1473
+
Поскольку вместо `count + 1`теперь передаётся `c => c + 1`, то [больше нет нужды указывать `count` в зависимостях эффекта.](/learn/removing-effect-dependencies#are-you-reading-some-state-to-calculate-the-next-state) А значит эффекту больше не приходится сбрасывать и заново устанавливать интервал каждый раз, когда изменяется `count`.
0 commit comments