programing

리액트 훅 - show Component Update를 구현하려면 어떻게 해야 합니까?

linuxpc 2023. 4. 1. 08:31
반응형

리액트 훅 - show Component Update를 구현하려면 어떻게 해야 합니까?

옵션의 두 번째 인수로 어레이를 전달함으로써 효과를 건너뛰도록 React에 지시할 수 있습니다.

예를 들어 다음과 같습니다.

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

하지만 비교를 제어하려면 어떻게 해야 할까요?저만의 비교 논리를 덧붙입니다.

게 요.React.memo함수를 두 번째 인수로 전달할 수 있습니다.

의 코멘트에서 Gabrile Petrioli는 wake Component Update를 구현하는 방법을 설명하는 React.memo 문서에 링크되어 있습니다.wake Component Update + useEffect + "react hooks"의 조합을 구글에서 검색했는데, 그 결과 이 메시지가 나타났습니다.그래서 링크된 문서를 사용하여 문제를 해결한 후 정보를 여기로 가져와야겠다고 생각했습니다.

다음은 show Component Update를 구현하는 오래된 방법입니다.

class MyComponent extends React.Component{
  shouldComponentUpdate(nextProps){
    return nextProps.value !== this.props.value;
  }
  render(){
    return (
     <div>{"My Component " + this.props.value}</div>
    );  
 }
}

새로운 리액트 훅 방식:

React.memo(function MyComponent (props) {

  return <div>{ "My Component " + props.value }</div>;

}) 

질문에서 더 많은 것을 요청하셨겠지만, 구글에서 오신 분들은 React Hooks를 사용하여 component Update를 구현하는 방법을 찾으시면 됩니다.

매뉴얼은 다음과 같습니다.how-do-i-implement-shouldcomponentupdate

에 PAT-O-MATION을 합니다.
또한 React.memo는 두 번째 파라미터(컴포넌트가 렌더링해야 하는지 여부를 결정하기 위해 사용할 수 있는 함수)를 받아들입니다.

함수가 true를 반환할 경우 컴포넌트는 해당 프로포트의 변경 시 재실행되지 않습니다.반대로 반환값이 false일 경우 갱신됩니다.

function SomeComp({prop1, prop2}) {
    return(
        ..
    )

}
React.memo(SomeComp, (props, nextProps)=> {
    if(props.prop1 === nextProps.prop1) {
        // don't re-render/update
        return true
    }
})

주의: 컴포넌트는 콜백 함수가 false를 반환할 때만 다시 렌더링되므로 위의 경우 prop2 값이 변경되어도 다시 렌더링되지 않습니다.

Avinash의 답변에 더해서.값을 반환하기 위한 중요한 참고 사항:

shouldComponentUpdate() {
  // returns true by default
  // return false if you don't need re-render
}

export default React.memo(Component, (props, nextProps) => {
  if(props.prop1 === nextProps.prop1) {
    // return true if you don't need re-render
  }
})

또는 useRef를 사용하여 데이터를 보관하고 useState ONLY를 사용하여 표시할 데이터를 저장하는 방법도 있습니다.메모 방식보다 이 방법이 더 효과적일 수 있습니다.최근 React.memo를 사용할 때 React가 불필요하게 렌더링되어 PIXI 디스플레이가 흐트러지는 경우가 있었습니다.아래에 있는 접근법으로 해결했습니다...안티패턴을 실행하지 않았기를 바랍니다:-)

const countRef = useRef(0);
const [countDisplay, setCountDisplay] = useState(0);

yourUpdateFunction = () => {
  // This is where count gets updated
  countRef.current = countRef.current + 1;
  if ((countRef.current % 2) === 0) setCountDisplay(countRef.current);
}

return (<p>countDisplay</p>);

true를 이은 두 로 true로 될 수 .useEffect또는useCallback또는useMemo강제 재인스톨:

function useShouldRecalculate(shouldRecalculateFn) {
  const prevValueRef = useRef(0);
  if(shouldRecalculateFn()) {
    // If we need to recalculate, change the value we return
    prevValueRef.current += 1;
  } // else we return the same value as the previous render, which won't trigger a recalculation
  return prevValueRef.current;
}

예를 들어, 개수가 짝수인 경우에만 문서 제목이 업데이트됩니다.

const shouldUpdateTitle = useShouldRecalculate(
  () => count % 2 === 0
);

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [shouldUpdateTitle]); // eslint-disable-line react-hooks/exhaustive-deps

왜 이렇게 하면 안 되는 거야?

대부분의 경우 이 작업을 권장하지 않습니다.

일반적으로, 관용적인 후크 API를 사용하여 동일한 작업을 수행하는 더 깔끔한 방법이 있을 것입니다. (위의 예시는 단순히 v-in-in-in-in-in-in-in-in-in-in-in-in-in-of-in-in-in-in-in-in-if문서 제목을 갱신하는 행을 차단합니다.)

아마도 더 중요한 것은deps인수는 단순히 최적화가 아니라 클로징 값을 최신 상태로 유지하고 다음과 같은 버그를 피하는 것입니다.

const [count, setCount] = useState(0)
const increment = useCallback(() => {
    // Bug: `count` is always 0 here, due to incorrect use of the `deps` argument
    setCount(count + 1)
}, [])

이 버그는 에 의해 검출됩니다.react-hooks/exhaustive-depslinter 규칙이지만 실행을 제어하기 위해 커스텀 로직을 사용하는 모든 장소에서 이 규칙을 비활성화해야 합니다.

커스텀 메모 로직을 사용하면 컴포넌트가 버그를 일으키기 쉽고 일반적으로 이해하기 어려워집니다.그래서 나는 이것을 고려했다.useShouldRecalculate최후의 수단을 쓰다

옵션의 두 번째 어레이 인수를 전달하면 어레이에 전달된 속성이 다음과 같이 변경될 경우 효과 함수가 시작됩니다.shouldComponentUpdate클래스 컴포넌트의 메서드는 소품이 컴포넌트에 전달될 때 실행됩니다.효과 함수는 모수의 값을 기반으로 효과를 적용할지 여부를 결정할 수 있습니다.

언급URL : https://stackoverflow.com/questions/54551949/react-hooks-how-do-i-implement-shouldcomponentupdate

반응형