Just want to know why my requestAnimationFrame doesn't update my react component repeatedly? it only returned count value the very first time,and then it ignore it. here's the code :
// ----- animation.js
import React from "react";
let count = 0;
export default function Update() {
return <>{UpdateComponents()}</>;
}
function UpdateComponents() {
count ;
window.requestAnimationFrame(UpdateComponents);
return <p>count: {count}</p>;
}
// ------ index.js
// ReactDOM.render(<Update />, document.getElementById("root"));
CodePudding user response:
requestAnimationFrame
is working as you expect, if you add a console.log(count)
after the place where you increment count
you'll see the value changing.
The reason it isn't showing up in your DOM is that no component is tracking the value of count
so nothing knows that it should be re-rendered. You'll need to hook your updates into state or prop changes in order to make the component show the 'live' count.
CodePudding user response:
It doesn't rerender because it doesn't trigger the reactdom In other for it to rerender repeatedly Use this piece of code
import React,{useState} from "react";
export default function Update() {
Let [count, setCount]=useState(0)
function UpdateComponents() {
var newcount=count 1;
setCount(newCount)
window.requestAnimationFrame(UpdateComponents);
UpdateComponents()
}
return <><p>count: {count}</p></>
}
This should work perfectly