English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 장에서는 컴포넌트 라이프사이클 메서드에 대해 논의할 것입니다.
componentWillMount
서버와 고객 서버에서 렌더링 전에 이미 실행되었습니다.
componentDidMount
고객 서버에서 첫 번째 렌더링 후 실행됩니다. AJAX 요청 및 DOM 또는 상태 업데이트를 수행해야 할 곳입니다. 이 메서드는 다른 JavaScript 프레임워크 및 지연 실행된 모든 함수(예:)setTimeout
또는 통합setInterval
。我们正在使用它来更新状态,以便我们可以触发其他生命周期方法。
componentWillReceiveProps
道具更新后立即调用,然后调用另一个渲染器。我们是从setNewNumber
更新状态时触发的。
shouldComponentUpdate
应该返回true
或false
值。这将确定组件是否将被更新。true
默认情况下设置为。如果您确定组件不需要在更新后state
或props
更新后呈现,则可以返回false
值。
componentWillUpdate
在渲染之前被调用。
componentDidUpdate
在渲染后立即调用。
componentWillUnmount
从dom卸下组件后调用。我们正在中卸载组件main.js
。
在下面的示例中,我们将state
在构造函数中设置初始值。将setNewnumber
用于更新的state
。모든 라이프사이클 메서드는 Content 컴포넌트 내부에 있습니다。
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 0 } this.setNewNumber = this.setNewNumber.bind(this) }; setNewNumber() { this.setState({data: this.state.data + 1) } render() { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } } class Content extends React.Component { componentWillMount() { console.log('컴포넌트 WILL MOUNT!') } componentDidMount() { console.log('컴포넌트 DID MOUNT!') } componentWillReceiveProps(newProps) { console.log('컴포넌트 WILL RECIEVE PROPS!') } shouldComponentUpdate(newProps, newState) { return true; } componentWillUpdate(nextProps, nextState) { console.log('Component WILL UPDATE!'); } componentDidUpdate(prevProps, prevState) { console.log('Component DID UPDATE!') } componentWillUnmount() { console.log('Component WILL UNMOUNT!') } render() { return ( <div> <h3{this.props.myNumber}</h3> </div> ); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/, document.getElementById('app')); setTimeout(() => { ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 10000);
초기 렌더링 후, 다음 스크린을 얻게 될 것입니다.