概述:
先看看React的架構圖:
https://bogdan-lyashenko.gith...
好好看一下上圖,初看看起來好像很複雜,但是事實上,它隻描述了兩個過程:挂載和更新。由于解除安裝在某種程度上就是“反挂載”,上圖中我們移除了解除安裝的過程,以使得流程圖看起來更簡單些。 當然,上圖不是100%比對源碼,但是已經能夠用來描述react架構的主要流程了。簡而言之,上圖覆寫了60%的代碼,但是剩下的40%基本上沒有什麼特别大的價值。是以為了簡化流程,這些40%的代碼都先暫時忽略了。
我們先在圖中看下子產品之間的依賴關系。
正如你所知,React是支援多個環境的:
1 手機端(RaectNative)
2 遊覽器端(ReactDOM)
3 服務端渲染
4 ReactART(使用React繪制矢量圖)
5 其他
正是為了支援多平台,上圖中很多檔案的代碼量是比圖裡展現的要多的多。 以下是包含多平台支援的流程圖。
正如你所見,一些内容被重複了兩次。也就是說,每個平台都有獨立的實作。比如說,ReactEventListener。很顯然,這個方法的實作在不同的平台是不同的。技術上來說,這些平台獨立子產品應該會以某種方法注入或者連接配接到目前的邏輯過程中,其實,這些子產品中有很多像這樣的injectors。因為它們的文法是标準合成模式的一部分,為了簡化,它們也被暫時忽略了。
我們先學習下React DOM在遊覽器中的邏輯流程。 這是用的最多的平台,同時這個函數基本上也覆寫了React架構的所有思想。
代碼示列:
學習一個架構或者庫的最後的辦法是什麼呢?閱讀和調試代碼。我們将調試兩個過程,React.render和component.setState,分别對應挂載和更新兩個階段。我們的執行個體代碼包含幾個帶有render方法的小元件,這樣會更有利于我們調試。
class ChildCmp extends React.Component {
render() {
return <div> {this.props.childMessage} </div>
}
}
class ExampleApplication extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'no message'};
}
componentWillMount() {
//...
}
componentDidMount() {
/* setTimeout(()=> {
this.setState({ message: 'timeout state message' });
}, 1000); */
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
return true;
}
componentDidUpdate(prevProps, prevState, prevContext) {
//...
}
componentWillReceiveProps(nextProps) {
//...
}
componentWillUnmount() {
//...
}
onClickHandler() {
/* this.setState({ message: 'click state message' }); */
}
render() {
return <div>
<button onClick={this.onClickHandler.bind(this)}> set state button </button>
<ChildCmp childMessage={this.state.message} />
And some text as well!
</div>
}
}
ReactDOM.render(
<ExampleApplication hello={'world'} />,
document.getElementById('container'),
function() {}
);
(未完待續)