React項目搭建與部署
一,介紹與需求
1.1,介紹
1.1.1,React簡介
-
- React 是一個用於構建用戶界面的 JAVASCRIPT 庫。
- React主要用於構建UI,很多人認為 React 是 MVC 中的 V(視圖)。
- React 起源於 Facebook 的內部項目,用來架設 Instagram 的網站,並於 2013 年 5 月開源。
- React 擁有較高的性能,代碼邏輯非常簡單,越來越多的人已開始關注和使用它。
1.1.2,React特點
-
- 聲明式設計:React采用聲明范式,可以輕松描述應用。
- 高效:React通過對DOM的模擬,最大限度地減少與DOM的交互。
- 靈活:React可以與已知的庫或框架很好地配合。
- JSX:JSX 是 JavaScript 語法的擴展。React 開發不一定使用 JSX ,但我們建議使用它。
- 組件:通過 React 構建組件,使得代碼更加容易得到復用,能夠很好的應用在大項目的開發中。
- 單向響應的數據流:React 實現了單向響應的數據流,從而減少了重復代碼,這也是它為什么比傳統數據綁定更簡單。
1.2,需求
二,環境搭建與項目框架
2.1,環境搭建
1,安裝NODE,
2,安裝webpack
1 npm install -g webpack
3,配置淘寶鏡像
使用淘寶定制的 cnpm (gzip 壓縮支持) 命令行工具代替默認的 npm
1 npm install -g cnpm --registry=https://registry.npm.taobao.org 2 npm config set registry https://registry.npm.taobao.org
4,安裝create-react-app
1 cnpm install -g create-react-app
5,創建項目
1 create-react-app my-project//創建項目 2 cd my-project/
6,本地服務啟動
1 npm run start//啟動本地server用於開發
2.2,項目框架
|-node_modules //項目包
|-public //一般用於存放靜態文件,打包時會被直接復制到輸出目錄(./buidle)
|-src //項目源代碼
| |-asserts //用於存放靜態資源,打包時會經過 webpack 處理
| |-asserts //用於存放靜態資源,打包時會經過 webpack 處理
| |-components //組件 存放 React 組件,一般是該項目公用的無狀態組件
| |-containers //頁面視圖
| |-routes //路由 存放需要 connect model 的路由組件
| |-containers //頁面視圖
| |-routes //路由 存放需要 connect model 的路由組件
| |-App.js //入口文件
| |-index //注冊路由與服務
| |- serviceWorker //開發配置
|-package.json //包管理代碼
|-.gitignore //Git忽略文件
三,常用集成與配置
3.1,路由集成與配置使用
React Router 是一個基於 React 之上的強大路由庫,它可以讓你向應用中快速地添加視圖和數據流,同時保持頁面與 URL 間的同步。react-router
1 npm install react-router@4.3.1 --save
- Router下面只能包含一個盒子標簽,類似這里的div。
- Link代表一個鏈接,在html界面中會解析成a標簽。作為一個鏈接,必須有一個to屬性,代表鏈接地址。這個鏈接地址是一個相對路徑。
- Route,是下面要說的組件,有一個path屬性和一個組件屬性(可以是component、render等等)。
-
1 render(){ 2 return ( 3 <Router> 4 <div> 5 <ul> 6 <li><Link to="/home">首頁</Link></li> 7 <li><Link to="/other">其他頁</Link></li> 8 </ul> 9 <Route path="/home" component={Home}/> 10 <Route path="/other" component={Other}/> 11 </div> 12 </Router> 13 ) 14 }
路由支持嵌套,代碼如下:
1 const Root = () => ( 2 <div> 3 <Switch> 4 <Route 5 path="/" 6 render={props => ( 7 <App> 8 <Switch> 9 <Route path="/" exact component={Home} /> 10 <Route path="/home" component={Home} /> 11 <Route path="/test" component={Test} /> 12 <Route path="/message/:id/:TestId" component={Message} /> 13 {/*路由不正確時,默認跳回home頁面*/} 14 <Route render={() => <Redirect to="/" />} /> 15 </Switch> 16 </App> 17 )} 18 /> 19 </Switch> 20 </div> 21 ); 22 23 export default Root;
3.2,redux集成與配置使用
React是單向數據流,所以有些情況下單單依賴React自身無法實現組件之間的通信,故此需要redux
需要安裝Redux相關依賴,由於不同版本之間可能存在兼容性問題,所以安裝的時候最好制定版本:
1 npm install redux@3.7.2 --save 2 npm install redux-thunk@2.1.0 --save 3 npm install react-redux@5.0.6 --save
然后就可以在項目中引入redux了,可以像如下方式組織目錄結構:
3.3,fetch集成與配置使用
關於請求數據有很多種方式,這里采用的是fetch
1 npm install fetch --save
可以簡單封裝一下,如下:
1 import 'whatwg-fetch' 2 import loggerService from './logger' 3 4 let notAuthorizedCounter = 0; 5 let fetchService = { 6 fetch: (url, method, header, body) => { 7 if (!header) { 8 header = {} 9 } 10 11 return fetchService[method.toLowerCase()](url, header, body).catch(function(exception) { 12 loggerService.log('fetchService failed:', exception); 13 14 // token過期,重新獲取token並發起請求 15 if (exception.code === '401' || exception.code === '403') { 16 notAuthorizedCounter++; 17 // 最多重試3次 18 if (notAuthorizedCounter > 2) { 19 notAuthorizedCounter = 0; 20 loggerService.warn("401 or 403 received. Max attemps reached."); 21 return; 22 } else { 23 return fetchService.fetch(url, method, header, body); 24 } 25 } 26 }); 27 }, 28 get: (url, header) => { 29 return fetch(url, { 30 method: 'GET', 31 headers: header 32 }).then((response) => { 33 return response.json(); 34 }); 35 }, 36 post: (url, header, body) => { 37 header['Content-Type'] = 'application/json'; 38 return fetch(url, { 39 method: 'POST', 40 headers: header, 41 body: JSON.stringify(body) 42 }).then((response) => { 43 return response.json(); 44 }); 45 } 46 }; 47 export default fetchService;
3.4,UI組件集成與配置使用
基於React的UI組件在這里推薦兩個,一個是螞蟻金服的Ant Design;另外一個是Material-UI。
兩個都很不錯,這里使用的是Ant Design。
1 npm install antd --save
請注意 react >= 16.6.3和react-dom >= 16.6.3 是對等依賴
1 npm install @material-ui/core
3.5,國際化方案
采用的是常用的react-intl
1 npm install react-intl --save
四,項目部署與問題
4.1,項目部署
首先對項目進行打包。
1 npm run build
通過以下命令可以在本地環境運行打包后的項目。
1 serve -s build
4.2,問題與注意事項
PropTypes 的使用
JavaScript 是弱類型語言,所以請盡量聲明 propTypes 對 props 進行校驗,以減少不必要的問題。
1 import React from 'react'; 2 import PropTypes from 'prop-types' 3 4 class PropTypesList extends React.Component { 5 static propTypes = {//校驗 6 title: PropTypes.string, 7 }; 8 static defaultProps = {//設置默認值 9 title:"PropTypes 的應用實例"//添加默認值 10 }; 11 constructor(props) { 12 super(props); 13 this.state = { 14 15 } 16 } 17 render() { 18 const { title} = this.props 19 return ( 20 <div> 21 <p>{title}</p> 22 </div> 23 ); 24 } 25 } 26 27 export default PropTypesList ;
內置的 prop type 有:
-
- PropTypes.array
- PropTypes.bool
- PropTypes.func
- PropTypes.number
- PropTypes.object
- PropTypes.string
- PropTypes.node,// 字符串,DOM 元素或包含這些類型的數組。
- PropTypes.element, // React 元素
- PropTypes.instanceOf(Message), // 用 JS 的 instanceof 操作符聲明 prop 為類的實例。
- PropTypes.oneOf(['News', 'Photos']), // 用 enum 來限制 prop 只接受指定的值。
- PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message) ]), // 指定的多個對象類型中的一個
- PropTypes.arrayOf(PropTypes.number),// 指定類型組成的數組
- PropTypes.objectOf(PropTypes.number), // 指定類型的屬性構成的對象
- PropTypes.shape({ color: PropTypes.string, fontSize:PropTypes.number }), // 特定形狀參數的對象
- PropTypes.func.isRequired, // 不可空的任意類型
- PropTypes.any.isRequired,// 以后任意類型加上 `isRequired` 來使 prop 不可空。
- customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error('Validation failed!'); } } },// 自定義驗證器。如果驗證失敗需要返回一個 Error 對象。不要直接 // 使用 `console.warn` 或拋異常,因為這樣 `oneOfType` 會失效。