React의 라이프사이클 사용법에 대한 자세한 설명

php中世界最好的语言
풀어 주다: 2018-05-24 14:21:05
원래의
1731명이 탐색했습니다.

이번에는 React에서 Life Cycle을 사용하는 방법에 대해 자세히 설명하겠습니다. React에서 Life Cycle을 사용할 때 주의사항은 무엇인가요?

라이프 사이클

React는 가상 DOM을 실제 DOM으로 렌더링하는 프로세스입니다. 이 프로세스를 컴포넌트의 라이프 사이클이라고 합니다. React는 이 주기를 3단계로 나누며, 각 단계에서는 will과 did라는 두 가지 처리 방법을 제공하고, did는 발생 후를 나타냅니다.

  • 마운팅: 구성 요소 렌더링 프로세스

    • comComponentWillMount()

    • comComponentDidMount()

  • 업데이트: 구성 요소 업데이트 프로세스

    • comComponentWillReceiveProps(nextProps)

    • shouldComponentUpdate(nextProps) , nextState)

    • comComponentWillUpdate(nextProps 객체, nextState 객체)

    • comComponentDidUpdate(prevProps 객체, prevState 객체)

  • Unmounting: 구성 요소 제거 프로세스

    • comWill Unmount( )

    • 이 단계에서는 해당 did 메소드가 없습니다

Mounting

은 DOM에서 구성 요소가 제거된 후 첫 번째 렌더링 또는 다시 렌더링을 의미합니다. 후자의 장면은 getDefaultProps

Execution order

  1. 를 실행하지 않습니다. ㅋㅋㅋ

    이 메소드는 렌더링 전에 호출되므로 이 메소드에서는 실제 DOM 요소를 얻을 수 없습니다.

    이 메서드는 처음으로 렌더링하기 전과 상태가 변경될 때 다시 렌더링하기 전에 트리거됩니다.
  2. comComponentDidMount

    이 메소드는 렌더링 후에 호출됩니다. 즉, 이 메소드는 실제 DOM 요소를 직접 얻을 수 있습니다.
  3. 이 메서드는 첫 번째 렌더링 후 및 상태가 변경되면 다시 렌더링한 후 트리거됩니다.
  4. var MountingComponent = React.createClass({
        componentWillMount: function(){
            console.log(this.refs.h1) // undefined
        },
        componentDidMount: function(){
            console.log(this.refs.h1) // h1 对象
        },
        render: function(){
            return <h1 ref="h1">Lifecycle-Mounting</h1>;
        }                
    })
    ReactDOM.render(<MountingComponent />, document.getElementById('p1'));
    로그인 후 복사

    Updating

  5. 컴포넌트의 props나 상태가 변경되면 트리거됩니다.
  6. 실행 순서

  7. comComponentWillReceiveProps

shouldComponentUpdate


comComponentWillUpdate


render

comComponentDidUpdate

    comComponentWillReceiveProps
  1. 구성 요소가 새 Prop을 받으면 호출됩니다. 이 메서드는 렌더링을 초기화할 때 호출되지 않습니다.

    메서드는 하나의 매개변수를 허용합니다
  2. newProps: 업데이트된 props
  3. 참고: props는 수동으로 변경할 수 없습니다. 일반적인 시나리오는 현재 구성 요소가 하위 구성 요소로 호출된 다음 구성 요소의 props가 상위 구성 요소에서 변경되는 것입니다.

    shouldComponentUpdate
  4. Component 마운팅 그 후, setState가 호출될 때마다 shouldComponentUpdate가 호출되어 구성 요소를 다시 렌더링해야 하는지 여부를 결정합니다. 기본적으로 true를 반환하며 다시 렌더링해야 합니다. 더 복잡한 응용 프로그램에서는 일부 데이터 변경 사항이 인터페이스 표시에 영향을 주지 않습니다. 여기서 판단하여 렌더링 효율성을 최적화할 수 있습니다.

    메서드는 두 개의 매개변수를 허용합니다.

    newProps: 업데이트된 props
  5. newState: 업데이트된 상태
  6. 메서드는 부울을 반환해야 합니다. true가 반환되면 후속 componentWillUpdate, render 및 componentDidUpdate가 실행됩니다. 그렇지 않으면 실행되지 않습니다.

    comComponentWillUpdate
  7. 는 구성 요소가 새 prop이나 상태를 받았지만 아직 렌더링되지 않은 경우 호출됩니다. 초기화 중에는 호출되지 않습니다.

    메서드는 두 개의 매개변수를 허용합니다.

    nextProps: 업데이트할 props
  8. nextState: 업데이트할 상태

comComponentDidUpdate

는 구성 요소가 업데이트를 완료한 후 즉시 호출됩니다. 초기화 중에는 호출되지 않습니다.
이 메소드는 두 개의 매개변수를 허용합니다.
prevProps: 업데이트 전의 소품
nextState: 업데이트 전의 상태

var UpdatingComponent = React.createClass({
    getInitialState: function() {
        return {
            data:0
        };
    },           
    setNewNumber: function() {
        //当 state 发生改变的时候,state 对应的组件会重新挂载
        //会触发 componentWillUpdate、componentDidUpdate
        this.setState({data: this.state.data + 1})
    },
    //参数 newProps:已更新的 props
    componentWillReceiveProps:function(newProps) {
        console.log('Component WILL RECEIVE PROPS!', newProps)
    },        
    //参数 newProps:已更新的 props
    //参数 newState:已更新的 state  
    //必须要返回 boolen,true 则执行componentWillUpdate、render、componentDidUpdate。反之则不执行。
    shouldComponentUpdate: function(newProps, newState){
        console.log('shouldComponentUpdate',newProps, newState);
        return (newState.data > 0 && newState.data % 2 == 0);
    },                          
    //参数 nextProps:将要更新的 props
    //参数 nextState:将要更新的 state
    componentWillUpdate: function(nextProps, nextState){
        console.log(nextProps, nextState, this.refs.p1)
    },
    //参数 prevProps:更新前的 props
    //参数 nextState:更新前的 state                
    componentDidUpdate: function(prevProps, prevState){
        console.log(prevProps, prevState) 
    },
    render: function(){
        return (
            <p>
                <button onClick={this.setNewNumber}>INCREMENT</button>
                <h3>{this.state.data}</h3>
            </p>
        );
    }                
})
ReactDOM.render(<UpdatingComponent/>, document.getElementById('p2'));
로그인 후 복사

Unmounting

在组件从 DOM 中移除的时候立刻被调用,这个阶段没有对应的 did 方法

componentWillUnmount

方法适用在父子组件的结构中,当某个条件符合的场景下,该子组件会被渲染

重新渲染的执行顺序

  1. getInitialState

  2. componentWillMount

  3. render

  4. componentDidMount

var ChildrenComponent = React.createClass({
    componentWillUnmount: function(){
        console.log('componentWillUnmount');
    },
    render: function(){
        return <h3>{this.props.myNumber}</h3>
    }
})
var UnmountingComponent = React.createClass({
    getInitialState: function() {
        return {
            data:0
        };
    },
    setNewNumber: function() {
        this.setState({data: this.state.data + 1})
    },
    render: function () {
        var content;
        //当条件不符合时 ChildrenComponent 会被移除,然后会触发方组件的 componentWillUnmount 方法
        //当条件重新符合时,会重新渲染组件 ChildrenComponent
        if(this.state.data % 2 == 0){
            content = <ChildrenComponent myNumber = {this.state.data}></ChildrenComponent>;
        } else {
            content = <h3>{this.state.data}</h3>;
        }
        return (
            <p>
                <button onClick = {this.setNewNumber}>INCREMENT</button>
                {content}
            </p>
        );
    }
})
ReactDOM.render(<UnmountingComponent/>, document.getElementById('p3'));
로그인 후 복사

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

react实现选中li高亮步骤详解

PromiseA+的实现步骤详解


위 내용은 React의 라이프사이클 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!