React 组件与 p5.js canvas 重复
React component is duplicated with p5.js canvas
我正在尝试使用单个 p5.js 草图创建一个 React 应用程序。但是,包含 p5 草图的组件在我的页面上被复制了。不确定为什么会这样呈现。
这里可以看到代码:https://stackblitz.com/edit/react-ts-kocwqw?file=App.tsx,Sketch.tsx,index.tsx
这里是反应组件定义:
App.tsx
import React = require('react');
import Sketch from './Sketch';
function App() {
return (
<div className="App">
<Sketch />
</div>
);
}
export default App;
Sketch.tsx
import React = require('react');
import { useEffect } from 'react';
import p5 from 'p5';
const Sketch = () => {
const p = (p5: any) => {
let radius: number;
p5.setup = () => {
p5.createCanvas(p5.windowWidth / 2, p5.windowHeight / 2);
p5.background(0);
radius = 0;
};
p5.draw = () => {
p5.ellipse(p5.width / 2, p5.height / 2, radius, radius);
if (radius < 70) radius++;
};
};
useEffect(() => {
new p5(p);
}, []);
return <></>;
};
export default Sketch;
index.tsx
import * as React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);
我可能在这里遗漏了什么?
解决方案是从 index.tsx
中删除 <StrictMode>
。
来自docs,
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking...
看起来严格模式是检测副作用的安全措施。
我正在尝试使用单个 p5.js 草图创建一个 React 应用程序。但是,包含 p5 草图的组件在我的页面上被复制了。不确定为什么会这样呈现。
这里可以看到代码:https://stackblitz.com/edit/react-ts-kocwqw?file=App.tsx,Sketch.tsx,index.tsx
这里是反应组件定义:
App.tsx
import React = require('react');
import Sketch from './Sketch';
function App() {
return (
<div className="App">
<Sketch />
</div>
);
}
export default App;
Sketch.tsx
import React = require('react');
import { useEffect } from 'react';
import p5 from 'p5';
const Sketch = () => {
const p = (p5: any) => {
let radius: number;
p5.setup = () => {
p5.createCanvas(p5.windowWidth / 2, p5.windowHeight / 2);
p5.background(0);
radius = 0;
};
p5.draw = () => {
p5.ellipse(p5.width / 2, p5.height / 2, radius, radius);
if (radius < 70) radius++;
};
};
useEffect(() => {
new p5(p);
}, []);
return <></>;
};
export default Sketch;
index.tsx
import * as React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);
我可能在这里遗漏了什么?
解决方案是从 index.tsx
中删除 <StrictMode>
。
来自docs,
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking...
看起来严格模式是检测副作用的安全措施。