Fixed draw function by wrapping it with usecallback

This commit is contained in:
Dmitriy Shishkov 2021-09-04 04:18:39 +03:00
parent 77661df39b
commit 7b34e5a5e5
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060

View File

@ -1,22 +1,42 @@
import { useCallback, useEffect, useState } from "react";
import { useRoomContext } from "../context"; import { useRoomContext } from "../context";
import { Canvas } from "./Canvas"; import { Canvas } from "./Canvas";
export type BuildingPlanProps = { width: number; height: number }; export type BuildingPlanProps = { width: number; height: number };
export const BuildingPlan = ({ width, height }: BuildingPlanProps) => { export const BuildingPlan = ({ width, height }: BuildingPlanProps) => {
const { state } = useRoomContext(); const { state, setState } = useRoomContext();
return ( const draw = useCallback(
<Canvas (ctx: CanvasRenderingContext2D) => {
height={height}
width={width}
draw={(ctx) => {
state.map.map(({ coordinates, size }, index) => { state.map.map(({ coordinates, size }, index) => {
const { free } = state.char[index]; const { free } = state.char[index];
ctx.fillStyle = free ? "green" : "gray"; ctx.fillStyle = free ? "green" : "gray";
ctx.fillRect(coordinates.x, coordinates.y, size.w, size.h); ctx.fillRect(coordinates.x, coordinates.y, size.w, size.h);
}); });
}} },
/> [state.char, state.map]
);
useEffect(() => {
setTimeout(
() =>
setState((p) => ({
...p,
char: [
{ free: false },
{ free: false },
{ free: false },
{ free: false },
],
})),
1000
);
}, []);
return (
<>
<Canvas height={height} width={width} draw={draw} />
</>
); );
}; };