programing

기능 컴포넌트 내의 ReactJS 라이프 사이클 방법

javamemo 2023. 3. 6. 20:37
반응형

기능 컴포넌트 내의 ReactJS 라이프 사이클 방법

클래스 내에 컴포넌트를 쓰는 대신 함수 구문을 사용하고 싶습니다.

덮어쓰려면componentDidMount,componentWillMount내부 기능 컴포넌트
그게 가능하기나 해?

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    const componentDidMount = () => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    };
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

편집: 라이프 사이클의 동작이나 기능 컴포넌트의 상태를 실장할 수 있습니다.현재의

후크는 클래스를 작성하지 않고 상태 및 기타 React 기능을 사용할 수 있는 새로운 기능 제안입니다.React에서는 v16.8.0의 일부로 릴리즈됩니다.

useEffect훅을 사용하여 라이프 사이클 동작을 복제할 수 있습니다.useState를 사용하여 함수 구성요소에 상태를 저장할 수 있습니다.

기본 구문:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction

다음과 같은 후크로 사용 사례를 구현할 수 있습니다.

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    useEffect(() => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    }, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

useEffect또한 컴포넌트가 마운트 해제되었을 때 실행되는 함수를 반환할 수도 있습니다.이것은, 청취자의 수신을 해제해, 다음의 동작을 복제하기 위해서 사용할 수 있습니다.componentWillUnmount:

예: componentWillUnmount

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
    return () => {
       window.removeEventListener('unhandledRejection', handler);
    }
}, [])

만들기 위해서useEffect는 특정 이벤트에 따라 변경 내용을 확인하기 위한 값 배열을 제공할 수 있습니다.

예: componentDidUpdate

componentDidUpdate(prevProps, prevState) {
     const { counter } = this.props;
     if (this.props.counter !== prevState.counter) {
      // some action here
     }
}

등가 후크

useEffect(() => {
     // action here
}, [props.counter]); // checks for changes in the values in this array

이 배열을 포함할 경우 구성 요소 범위의 모든 값(프롭, 상태)을 포함해야 합니다. 그렇지 않으면 이전 렌더링의 값을 참조하게 될 수 있습니다.

사용할 때 몇 가지 미묘한 점이 있습니다.useEffectAPI를 확인해 주세요.


v16.7.0 이전

기능 컴포넌트의 속성은 Response 라이프 사이클 기능 또는 기능에 액세스할 수 없다는 것입니다.this키워드를 지정합니다.확장해야 합니다.React.Componentclass(클래스)를 클릭합니다.

class Grid extends React.Component  {
    constructor(props) {
       super(props)
    }

    componentDidMount () {
        if(!this.props.fetched) {
            this.props.fetchRules();
        }
        console.log('mount it!');
    }
    render() {
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
  }
}

함수 구성요소는 추가 논리 없이 구성요소를 렌더링하려는 경우에만 유용합니다.

react-pure-life-cycle을 사용하여 기능 컴포넌트에 라이프 사이클 기능을 추가할 수 있습니다.

예:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
  componentDidMount(props) {
    console.log('I mounted! Here are my props: ', props);
  }
};

const Channels = props => (
<h1>Hello</h1>
)

export default lifecycle(methods)(Channels);

훅을 사용하여 나만의 '라이프 사이클 방법'을 만들어 향수를 극대화할 수 있습니다.

유틸리티 기능:

import { useEffect, useRef } from "react";

export const useComponentDidMount = handler => {
  return useEffect(() => handler(), []);
};

export const useComponentDidUpdate = (handler, deps) => {
  const isInitialMount = useRef(true);

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;

      return;
    }

    return handler();
  }, deps);
};

export const useComponentWillUnmount = handler => {
  return useEffect(() => handler, []);
};

사용방법:

import {
  useComponentDidMount,
  useComponentDidUpdate,
  useComponentWillUnmount
} from "./utils";

export const MyComponent = ({ myProp }) => {
  useComponentDidMount(() => {
    console.log("Component did mount!");
  });

  useComponentDidUpdate(() => {
    console.log("Component did update!");
  });

  useComponentDidUpdate(() => {
    console.log("myProp did update!");
  }, [myProp]);

  useComponentWillUnmount(() => {
    console.log("Component will unmount!");
  });

  return <div>Hello world</div>;
};  

해결책 1: 새로운 리액트 HOOKS API를 사용할 수 있습니다.현재 리액트 v16.8.0

후크를 사용하면 클래스 없이 React의 기능을 더 많이 사용할 수 있습니다.Hook은 이미 알고 있는 React 개념(소품, 상태, 컨텍스트, 참조 및 라이프 사이클)에 대한 보다 직접적인 API를 제공합니다.Hooks는 Recompose로 해결되는 모든 문제를 해결합니다.

(acdlite, 2018년 10월 25일)의 작성자의 주의사항:

안녕하세요. 제가 3년 전에 Recompose를 만들었습니다.그로부터 약 1년 후, 저는 리액트 팀에 합류했습니다.오늘 우리는 Hooks에 대한 제안을 발표했습니다.Hooks는 제가 3년 전에 Recompose로 해결하려고 했던 모든 문제를 해결하고 그 외에도 더 많은 문제를 해결합니다.이 패키지의 액티브한 유지보수를 중단하고(아마도 향후 React 릴리스와의 호환성을 위해 버그 수정이나 패치를 제외), 대신 Hooks를 사용할 것을 권장합니다.Recompose를 사용하는 기존 코드는 계속 작동하므로 새로운 기능은 기대하지 마십시오.

솔루션 2:

후크를 지원하지 않는 리액트 버전을 사용하는 경우(기능 컴포넌트 및 고차 컴포넌트용 리액트 유틸리티 벨트)를 사용하십시오.사용할 수 있습니다.recompose착착을 붙이기 lifecycle hooks, state, handlers etc이치노

이것은 라이프 사이클 HOC를 통해 라이프 사이클 메서드를 연결하는 렌더리스 컴포넌트입니다.

// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

function RenderlessComponent() {
  return null; 
}

export default lifecycle({

  componentDidMount() {
    const { checkIfAuthed } = this.props;
    // Do they have an active session? ("Remember me")
    checkIfAuthed();
  },

  componentWillReceiveProps(nextProps) {
    const {
      loadUser,
    } = this.props;

    // Various 'indicators'..
    const becameAuthed = (!(this.props.auth) && nextProps.auth);
    const isCurrentUser = (this.props.currentUser !== null);

    if (becameAuthed) {
      loadUser(nextProps.auth.uid);
    }

    const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
    if (shouldSetCurrentUser) {
      const currentUser = nextProps.users[nextProps.auth.uid];
      if (currentUser) {
        this.props.setCurrentUser({
          'id': nextProps.auth.uid,
          ...currentUser,
        });
      }
    }
  }
})(RenderlessComponent);

component Did Mount(컴포넌트 마운트)

useEffect(()=>{
   // code here
})

component Will Mount(컴포넌트 마운트)

useEffect(()=>{

   return ()=>{ 
                //code here
              }
})

componentDidUpdate

useEffect(()=>{

    //code here
    // when userName state change it will call     
},[userName])

설명서에 따르면:

import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:

useEffect(() => {


});

자세한 내용은 리액트 매뉴얼을 참조하십시오.

간결하고 달콤한 대답

component Did Mount(컴포넌트 마운트)

useEffect(()=>{
   // code here
})

component Will 언마운트

useEffect(()=>{

   return ()=>{ 
                //code here
              }
})

componentDidUpdate

useEffect(()=>{

    //code here
    // when userName state change it will call     
},[userName])

create-react 클래스 모듈을 사용할 수 있습니다.공식 문서

물론 먼저 설치해야 합니다.

npm install create-react-class

다음은 작업 예시입니다.

import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')


let Clock = createReactClass({
    getInitialState:function(){
        return {date:new Date()}
    },

    render:function(){
        return (
            <h1>{this.state.date.toLocaleTimeString()}</h1>
        )
    },

    componentDidMount:function(){
        this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
    },

    componentWillUnmount:function(){
        clearInterval(this.timerId)
    }

})

ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
)

react 16.8을 사용하면 react Hooks를 사용할 수 있습니다.리액트 훅은 기능 컴포넌트에서 리액트 상태와 라이프 사이클 기능을 "훅"할 수 있는 기능입니다.문서

import React, { useState, useEffect } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);

  // componentDidMount
  useEffect(() => {
    console.log("The use effect ran");
  }, []);

  // // componentDidUpdate
  useEffect(() => {
    console.log("The use effect ran");
  }, [count, count2]);

  // componentWillUnmount
  useEffect(() => {
    console.log("The use effect ran");
    return () => {
      console.log("the return is being ran");
    };
  }, []);

  useEffect(() => {
    console.log(`The count has updated to ${count}`);
    return () => {
      console.log(`we are in the cleanup - the count is ${count}`);
    };
  }, [count]);

  return (
    <div>
      <h6> Counter </h6>
      <p> current count: {count} </p>
      <button onClick={() => setCount(count + 1)}>increment the count</button>
      <button onClick={() => setCount2(count2 + 1)}>increment count 2</button>
    </div>
  );
};

export default Counter;

언급URL : https://stackoverflow.com/questions/44506207/reactjs-lifecycle-method-inside-a-function-component

반응형