Programing

use로 선언된 변수를 사용하는 방법다른 함수에서 효과()?

c10106 2022. 3. 31. 21:45
반응형

use로 선언된 변수를 사용하는 방법다른 함수에서 효과()?

p.s는 내가 가지고 있던 문제를 해결했지만, 그래도 시간이 있다면 이것과 내 코드에 대한 너의 생각을 듣고 싶다 :)

렌더링을 완료한 후에만 해당 변수에 값을 할당할 수 있으므로 useEffect()에서 해당 변수를 선언해야 하며, 글로벌 범위에서 값을 할당하는 것은 불가능하다고 가정한다(렌더보다 먼저 실행됨).그러나 나는 또한 그 변수를 다른 useEffect()에도 사용하고 싶지만, 함수 내에서 선언되고 글로벌 범위에 속하지 않기 때문에 사용할 수 없다.또한 useEffect -s가 두 개 있는 것이 정상인가?하나는 캔버스의 컨텍스트를 잡고 그 컨텍스트를 일관적으로 유지하는 것(모든 DOM 업데이트에서 새로운 컨텍스트를 잡지 않는 것, []을 첫 번째 useEffect의 두 번째 인수로 넣지 않을 때 일어나는 것)이 필요하다.그리고 또 하나는 국가가 바뀌면서 그 독특한 맥락으로 일을 하는 것이다.그게 말이 되는 건가요?내 코드:

import React, { useState, useRef, useEffect } from "react";
import { degreesToRadiansFlipped } from "./helpers/degreesToRadiansFlipped";
function Circle() {
  let [degree, setDegree] = useState(0);
  const canvas = useRef();
  const inputField = useRef();
  const coordinateX = Math.cos(degreesToRadiansFlipped(degree)) * 100 + 250;
  const coordinateY = Math.sin(degreesToRadiansFlipped(degree)) * 100 + 250;

  useEffect(() => {
    const context = canvas.current.getContext("2d");
    drawCircle(context, coordinateX, coordinateY);
    return context;
    /*return function cleanUp() {
      context.clearRect(0, 0, 500, 500);
      context.beginPath();
      drawCircle(context, coordinateX, coordinateY);
    };*/
  }, []);
  useEffect(() => {
    drawCircle(context, coordinateX, coordinateY);
  }, [degree]);
  let drawCircle = function(context, x, y) {
    context.beginPath();
    //arc has option to make it anti-clockwise, making flipping radians redundant
    context.arc(250, 250, 100, 0, Math.PI * 2);
    context.moveTo(250, 250);
    context.lineTo(x, y);
    context.stroke();
  };

  return (
    <div>
      <canvas ref={canvas} width={500} height={500}></canvas>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          setDegree(inputField.current.value);
        }}
      >
        <input type="text" ref={inputField}></input>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default Circle;

그래, 두 번째 매개 변수에서 너처럼 다른 인수가 있을 때, 배수가 효과 를 사용하도록 하는 것이 타당하다.

useEffec 외부의 변수를 정의되지 않은 것으로 선언할 수 있다.

let context = undefined // is not constant
  useEffect(() => {
    context = canvas.current.getContext("2d");
    drawCircle(context, coordinateX, coordinateY);
    return context;
    /*return function cleanUp() {
      context.clearRect(0, 0, 500, 500);
      context.beginPath();
      drawCircle(context, coordinateX, coordinateY);
    };*/
  }, []);
  useEffect(() => {
    drawCircle(context, coordinateX, coordinateY);
  }, [degree]);

기능 범위에서는 이러한 방법을 사용할 수 있다.

변수를 다음 외부로 선언하는 경우useEffect각 렌더링 후에 어떤 임무도 잃게 된다.

더 나은 접근방식은 다음 제품을 사용하는 것이다.useRef돌연변이 값을 후크하여.current재산그렇지 않으면 안에 보관하는 것이 상책이다.useEffect.

참조URL: https://stackoverflow.com/questions/58140009/how-to-use-variable-declared-in-useeffect-in-another-function

반응형