최고의 성분 수명 반응 튜토리얼 2024년, 이 튜토리얼에서는 성분 수명 반응를 배울 수 있습니다.
이 장에서 우리는 생명주기가 구성 요소 반응에 대해 설명합니다.
부품의 수명주기가 세 가지 상태로 나눌 수있다 :
수명의 방법은 :
componentWillMount 호, 또한 클라이언트 측에서 서비스를 렌더링하기 전에.
componentDidMount : 첫 번째 호출은 클라이언트를 렌더링하는 후.구성 요소가 DOM 구조에 대응하는 생성 된 후 this.getDOMNode 통해 액세스 할 수있다 (). 다른 자바 스크립트 프레임 워크와 함께 사용하려는 경우에 setInterval,이 방법에서는 setTimeout 전화를 걸거나 등 (다른 단위 작업이 차단 UI를 방지하기 위해) AJAX 요청을 보낼 수 있습니다.
구성 요소가 새로운 소품을받을 때componentWillReceiveProps가 호출됩니다.이 방법은 초기화 렌더링 중에 호출되지 않습니다.
shouldComponentUpdate는 부울 값을 반환합니다.구성 요소가 새로운 소품 또는 상태를 수신 할 때 호출된다. 그것은하지 초기화시 호출 또는 forceUpdate를 사용한다.
업데이트 된 구성 요소를 확인하기 위해 필요하지 않은 때 사용할 수있다.
구성 요소의componentWillUpdate 새로운 소품이나 상태를 수신하지 있지만라고 렌더링하고있다.그것은 초기화하는 동안 호출되지 않습니다.
업데이트 후 즉시 호출 완료componentDidUpdate의 구성 요소입니다.그것은 초기화하는 동안 호출되지 않습니다.
구성 요소는 DOM에서 제거 될 때componentWillUnmount 즉시했다.
이러한 방법에 대한 자세한 설명, 당신은 참조 할 수 있습니다 공식 문서 .
안녕하세요 구성 요소 후 다음 예는 타이머 componentDidMount 방법 매 100 밀리 초 투명도 리 세트 성분과 재 렌더링 설정,로드 :
var Hello = React.createClass({ getInitialState: function () { return { opacity: 1.0 }; }, componentDidMount: function () { this.timer = setInterval(function () { var opacity = this.state.opacity; opacity -= .05; if (opacity < 0.1) { opacity = 1.0; } this.setState({ opacity: opacity }); }.bind(this), 100); }, render: function () { return ( <div style={{opacity: this.state.opacity}}> Hello {this.props.name} </div> ); } }); ReactDOM.render( <Hello name="world"/>, document.body );
다음 예는상태를 업데이트,setNewnumber를상태를초기화된다. 모든 라이프 사이클콘텐츠 구성 요소입니다.
var Button = React.createClass({ getInitialState: function() { return { data:0 }; }, setNewNumber: function() { this.setState({data: this.state.data + 1}) }, render: function () { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } }) var Content = React.createClass({ componentWillMount:function() { console.log('Component WILL MOUNT!') }, componentDidMount:function() { console.log('Component DID MOUNT!') }, componentWillReceiveProps:function(newProps) { console.log('Component WILL RECIEVE PROPS!') }, shouldComponentUpdate:function(newProps, newState) { return true; }, componentWillUpdate:function(nextProps, nextState) { console.log('Component WILL UPDATE!'); }, componentDidUpdate:function(prevProps, prevState) { console.log('Component DID UPDATE!') }, componentWillUnmount:function() { console.log('Component WILL UNMOUNT!') }, render: function () { return ( <div> <h3>{this.props.myNumber}</h3> </div> ); } }); ReactDOM.render( <div> <Button /> </div>, document.getElementById('example') );