So listen, I don't know why you're holding two randoms (one in the .css file and other in the component itself).
The @random in your css will only evaluate once, when you do a refresh in the browser. You use something like styled-components to make your styles dynamic based on states in your component.
The other workaround is to override (as you are doing) the left and top styles from within the component:
const App = () => {
const [date, setDate] = useState('');
const [circleBoolean, setCircleBoolean] = useState(false);
const [randomNumber, setRandom] = useState();
useEffect(() => {
const interval = setInterval(() => {
doThings();
}, 2000);
return () => clearInterval(interval);
}, []);
function doThings() {
setRandom(() => {
return Math.random() * 100;
});
setCircleBoolean((prev) => {
return !prev;
});
setDate(moment().format('MMMM Do YYYY, h:mm:ss a'));
}
return (
<div className="App">
<div className="bg">
<div style={{ top: randomNumber + '%', left: randomNumber + '%' }} className={circleBoolean ? 'circle' : ''} />
<div className="card">
<p className="card-info">{date}</p>
</div>
</div>
</div>
);
};
Here, I changed your "style" prop and moved the random_number into its own state randomNumber.
OLD -----
First your useEffect is triggered whenever circleBoolean is changed, each two seconds. Then it'll be called again and create another interval, and so on. Here, you need an array of zero dependencies for your useEffect. That way the interval will be created just once, once the component renders the first time.
Okey, then each two seconds the interval function will execute a state change in setCircleBoolean. The correct way to do so (in this case) would be:
setCircleState((prev) => {
return !prev;
});
This way, React will wait for the state change and triggers the re-render more accurately.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…