Why does every time I save my Vite React project, a new canvas element is added to the page body instead of replacing the existing canvas element?
P粉186904731
P粉186904731 2024-03-30 09:57:49
0
1
480

I'm trying to start learning ThreeJs (I'm also new to Javascript web development). After watching some tutorials, I started with Vite and React, then started with a basic rotating cube. This part works.

But from what I've read about vite, saving the file I'm working on should be enough to reload it onto the page. But in fact, it's not. I checked the page content and every time I save the file, 2x the same canvas element is appended to the page body (instead of replacing the existing one), which means I have to scroll down to the bottom of the page to see the new content (or reloading the page, which defeats the purpose of Vite's fast refresh feature).

What did i do wrong? I built a basic Vite project, added a component to the app, and followed the tutorial to do a basic cube rendering, bypassing Vite's fast refresh along the way. help?

Github: https://github.com/amdreallyfast/ThreeJsTutorials/tree/main/npmfrontend

Reappearance:

clone
cd <directory>/npmfrontend
npm install 
npm run dev
Open page in browser
Inspect page -> Elements
Open SceneRenderer.jsx
Make change and save (ex: rotation speed; repeat multiple times)
Notice how the body element on the loaded page keeps appending new canvases

P粉186904731
P粉186904731

reply all(1)
P粉788571316

You will call renderScene every time in the render function. In React, the render function is called every time it is re-rendered/updated.

So every update (hot reload in your case) triggers the render function, creating a new DOM element.

Manually creating DOM elements when using React is generally an anti-pattern (unless you're completely sure of what you're doing). I recommend using the Three.js React renderer like this: https://github.com/pmndrs/react-三fiber

If for some reason you really want to do this, you might consider calling it during the componentDidMount lifecycle of your React application, and make sure to clean up during the componentWillUnmount lifecycle it. You can read more about them here: https://react.dev/reference/react/Component#Component is mounted

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template