# React 技術棧
React 是目前最熱門的前端框架。
* Facebook 公司2013年推出
* 現在最好的社區支持和生態圈
* 大量的第三方工具
[](https://github.com/ruanyf/jstraining/blob/master/docs/images/react-logo.png)
[TOC=2,2]
## React 的優點
* 組件模式:代碼復用和團隊分工
* 虛擬 DOM:性能優勢
* 移動端支持:跨終端
## React 的缺點
* 學習曲線較陡峭
* 全新的一套概念,與其他所有框架截然不同
* 只有采用它的整個技術棧,才能發揮最大威力
總結:React 非常先進和強大,但是學習和實現成本都不低
## JSX 語法
React 使用 JSX 語法,JavaScript 代碼中可以寫 HTML 代碼。
~~~
let myTitle = <h1>Hello, world!</h1>;
~~~
## JSX 語法解釋
(1)JSX 語法的最外層,只能有一個節點。
~~~
// 錯誤
let myTitle = <p>Hello</p><p>World</p>;
~~~
(2)JSX 語法中可以插入 JavaScript 代碼,使用大括號。
~~~
let myTitle = <p>{'Hello ' + 'World'}</p>
~~~
## Babel 轉碼器
JavaScript 引擎(包括瀏覽器和 Node)都不認識 JSX,需要首先使用 Babel 轉碼,然后才能運行。
~~~
<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="babel.min.js"></script>
<script type="text/babel">
// ** Our code goes here! **
</script>
~~~
React 需要加載兩個庫:React 和 React-DOM,前者是 React 的核心庫,后者是 React 的 DOM 適配庫。
Babel 用來在瀏覽器轉換 JSX 語法,如果服務器已經轉好了,瀏覽器就不需要加載這個庫。
## 課堂練習:JSX 語法
瀏覽器打開`demos/jsx-demo/index.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#jsx),完成練習。
~~~
ReactDOM.render(
<span>Hello World!</span>,
document.getElementById('example')
);
~~~
## 示例:React 組件
React 允許用戶定義自己的組件,插入網頁。
瀏覽器打開`demos/react-component-demo/index1.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#react-%E7%BB%84%E4%BB%B6%E8%AF%AD%E6%B3%95),仔細查看源碼。
~~~
class MyTitle extends React.Component {
render() {
return <h1>Hello World</h1>;
}
};
ReactDOM.render(
<MyTitle/>,
document.getElementById('example')
);
~~~
## 課堂練習:組件的參數
組件可以從外部傳入參數,內部使用`this.props`獲取參數。
打開`demos/react-component-demo/index2.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#react-%E7%BB%84%E4%BB%B6%E7%9A%84%E5%8F%82%E6%95%B0),完成練習。
~~~
class MyTitle extends React.Component {
render() {
return <h1
style={{color: this.props.color}}
>Hello World</h1>;
}
};
<MyTitle color="red" />,
~~~
## 示例:組件的狀態
組件往往會有內部狀態,使用`this.state`表示。
瀏覽器打開`demos/react-component-demo/index3.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#react-%E7%BB%84%E4%BB%B6%E7%9A%84%E7%8A%B6%E6%80%81),仔細查看源碼。
[](https://github.com/ruanyf/jstraining/blob/master/docs/images/react-component-state.png)
## 課堂練習:React 組件實戰
瀏覽器打開`demos/react-component-demo/index4.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#react-%E7%BB%84%E4%BB%B6%E5%AE%9E%E6%88%98),完成練習。
## 組件的生命周期
React 為組件的不同生命階段,提供了近十個鉤子方法。
* `componentWillMount()`:組件加載前調用
* `componentDidMount()`:組件加載后調用
* `componentWillUpdate()`: 組件更新前調用
* `componentDidUpdate()`: 組件更新后調用
* `componentWillUnmount()`:組件卸載前調用
我們可以利用這些鉤子,自動完成一些操作。
## 課堂練習:組件的生命周期
組件可以通過 Ajax 請求,從服務器獲取數據。Ajax 請求一般在`componentDidMount`方法里面發出。
~~~
componentDidMount() {
const url = '...';
$.getJSON(url)
.done()
.fail();
}
~~~
打開`demos/react-lifecycle-demo/index.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#react-%E7%BB%84%E4%BB%B6%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F),完成練習。
## React 組件庫
React 的一大優勢,就是網上有很多已經寫好的組件庫,可以使用。
React-Bootstrap:[https://react-bootstrap.github.io/](https://react-bootstrap.github.io/)
[](https://github.com/ruanyf/jstraining/blob/master/docs/images/react-bootstrap.png)
## 示例:ReCharts
ReCharts 是一個 React 圖表組件庫。[http://recharts.org/](http://recharts.org/)
瀏覽器打開`demos/recharts-demo/index.html`,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#recharts),仔細查看源碼。
~~~
<LineChart width={1000} height={400} data={data}>
<XAxis dataKey="name"/>
<YAxis/>
<CartesianGrid stroke="#eee" strokeDasharray="5 5"/>
<Line type="monotone" dataKey="uv" stroke="#8884d8" />
<Line type="monotone" dataKey="pv" stroke="#82ca9d" />
</LineChart>
~~~
## React 應用的架構
React 只是一個 DOM 的抽象層,并沒有解決應用程序的架構問題:大型應用程序應該如何組織代碼?
Facebook 提出 Flux 架構的概念。
[](https://github.com/ruanyf/jstraining/blob/master/docs/images/flow.png)
最大特點:數據單向流動
## 目前最流行的兩個 React 框架
* MobX:采用觀察者模式,自動響應數據變化
* Redux:Flux 的函數式實現
## MobX 架構
MobX 的核心概念,就是組件是觀察者,一旦`Store`有變化,會立刻被組件觀察到,從而引發重新渲染。
~~~
@observer
class App extends React.Component {
render() {
// ...
}
}
~~~
## 示例:MobX
進入`demos/mobx-demo`目錄,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#mobx),理解 MobX 框架。
UI 層是觀察者,Store 是被觀察者。
Store 所有的屬性,分成兩大類:直接被觀察的屬性和自動計算出來的屬性。
~~~
class Store {
@observable name = 'Bartek';
@computed get decorated() {
return `${this.name} is awesome!`;
}
}
~~~
UI 會觀察到 Store 的變化,自動重新渲染。
## Redux 架構
Redux 的核心概念
* 所有的狀態存放在`Store`。組件每次重新渲染,都必須由狀態變化引起。
* 用戶在 UI 上發出`action`。
* `reducer`函數接收`action`,然后根據當前的`state`,計算出新的`state`。
[](https://github.com/ruanyf/jstraining/blob/master/docs/images/redux-architecture.png)
## 示例:Redux
進入`demos/redux-demo`目錄,按照[《操作說明》](https://github.com/ruanyf/jstraining/blob/master/demos/README.md#redux),理解 Redux 框架。
* Redux 將組件分成 UI 組件和容器組件兩類。
* UI 組件是純組件,需要用戶自己寫。
~~~
<div className="index">
<p>{this.props.text}</p>
<input
defaultValue={this.props.name}
onChange={this.props.onChange}
/>
</div>
~~~
容器組件在用戶給出配置以后,由 Redux 生成。
~~~
// MyComponent 是純的 UI 組件
const App = connect(
mapStateToProps,
mapDispatchToProps
)(MyComponent);
~~~
* mapStateToProps: 定義 UI 組件參數與 State 之間的映射
* mapDispatchToProps:定義 UI 組件與 Action 之間的映射
`reducer`是一個純函數,用來接收`action`,算出新的`state`。
~~~
function reducer(state = {
text: '你好,訪問者',
name: '訪問者'
}, action) {
switch (action.type) {
case 'change':
return {
name: action.payload,
text: '你好,' + action.payload
};
}
}
~~~
* `Store`由 Redux 提供的`createStore`方法生成,該方法接受`reducer`作為參數。
* 為了把`Store`傳入組件,必須使用 Redux 提供的`Provider`組件在應用的最外面,包裹一層。
~~~
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.body.appendChild(document.createElement('div'))
);
~~~