既然學習react,那就從hello word開始。固然必不可少的須要引入react,這裏我使用的是官網的 Creating a New Application 方式,經過如下命令行操做便可在項目中使用react了,固然官網還提供了其餘引入方式。html
npm install -g create-react-app create-react-app test-react cd test-react npm start
項目工程目錄以下:react
在我理解看來,react項目文件入口便是index.js
文件,那麼從index.js
中編寫Hello Word。git
輸出結果:github
從下面的代碼中,去弄弄清楚react
的組件生命週期。npm
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('root') );
1) When <Clock />
is passed to ReactDOM.render()
, React calls the constructor of the Clock
component. Since Clock needs to display the current time, it initializes this.state
with an object including the current time. We will later update this state.segmentfault
2) React then calls the Clock
component's render()
method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock's
render output.app
3) When the Clock
output is inserted in the DOM, React calls the componentDidMount()
lifecycle hook. Inside it, the Clock component asks the browser to set up a timer to call tick()
once a second.ide
4) Every second the browser calls the tick()
method. Inside it, the Clock
component schedules a UI update by calling setState()
with an object containing the current time. Thanks to the setState()
call, React knows the state has changed, and calls render()
method again to learn what should be on the screen. This time, this.state.date
in the render()
method will be different, and so the render output will include the updated time. React updates the DOM accordingly.函數
5) If the Clock
component is ever removed from the DOM, React calls the componentWillUnmount()
lifecycle hook so the timer is stopped.學習
react
組件生命週期大體有下面幾個狀態:
Mounting
:已插入真實 DOMUpdating
:正在被從新渲染Unmounting
:已移出真實 DOM
React 爲每一個狀態都提供了兩種處理函數,will 函數在進入狀態以前調用,did 函數在進入狀態以後調用,三種狀態共計五種處理函數。
componentWillMount()
componentDidMount()
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object nextProps, object nextState)
componentWillUnmount()
官方文檔所述圖片:
注:文章末尾段react
組件生命週期引入自https://segmentfault.com/a/11...