React項目搭建與部署

React項目搭建與部署

一,介紹與需求

1.1,介紹

1.1.1,React簡介

    • React 是一個用於構建用戶界面的 JAVASCRIPT 庫。
    • React主要用於構建UI,不少人認爲 React 是 MVC 中的 V(視圖)。
    • React 起源於 Facebook 的內部項目,用來架設 Instagram 的網站,並於 2013 年 5 月開源。
    • React 擁有較高的性能,代碼邏輯很是簡單,愈來愈多的人已開始關注和使用它。

1.1.2,React特色

    1. 聲明式設計:React採用聲明範式,能夠輕鬆描述應用。
    2. 高效:React經過對DOM的模擬,最大限度地減小與DOM的交互。
    3. 靈活:React能夠與已知的庫或框架很好地配合。
    4. JSX:JSX 是 JavaScript 語法的擴展。React 開發不必定使用 JSX ,但咱們建議使用它。
    5. 組件:經過 React 構建組件,使得代碼更加容易獲得複用,可以很好的應用在大項目的開發中。
    6. 單向響應的數據流:React 實現了單向響應的數據流,從而減小了重複代碼,這也是它爲何比傳統數據綁定更簡單。

1.2,需求

二,環境搭建與項目框架

2.1,環境搭建

1,安裝NODE,html

2,安裝webpacknode

1  npm install -g webpack 

3,配置淘寶鏡像
react

使用淘寶定製的 cnpm (gzip 壓縮支持) 命令行工具代替默認的 npmwebpack

1 npm install -g cnpm --registry=https://registry.npm.taobao.org
2 npm config set registry https://registry.npm.taobao.org

4,安裝create-react-appgit

1 cnpm install -g create-react-app

5,建立項目

1 create-react-app my-project//建立項目
2 cd my-project/ 

6,本地服務啓動github

1 npm run start//啓動本地server用於開發

2.2,項目框架 

|-node_modules             //項目包
|-public             //通常用於存放靜態文件,打包時會被直接複製到輸出目錄(./buidle)
|-src               //項目源代碼
  |  |-asserts         //用於存放靜態資源,打包時會通過 webpack 處理
  |  |-components     //組件 存放 React 組件,通常是該項目公用的無狀態組件
  |  |-containers          //頁面視圖
  |  |-routes         //路由 存放須要 connect model 的路由組件
  |  |-App.js         //入口文件
  |  |-index         //註冊路由與服務
  |  |- serviceWorker        //開發配置
|-package.json      //包管理代碼
|-.gitignore //Git忽略文件

三,經常使用集成與配置

3.1,路由集成與配置使用

React Router 是一個基於 React 之上的強大路由庫,它可讓你嚮應用中快速地添加視圖和數據流,同時保持頁面與 URL 間的同步。react-routerweb

1 npm install react-router@4.3.1 --save

  1. Router下面只能包含一個盒子標籤,相似這裏的div。 
  2. Link表明一個連接,在html界面中會解析成a標籤。做爲一個連接,必須有一個to屬性,表明連接地址。這個連接地址是一個相對路徑。 
  3. Route,是下面要說的組件,有一個path屬性和一個組件屬性(能夠是component、render等等)。
  4.  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 }

路由支持嵌套,代碼以下:npm

 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自身沒法實現組件之間的通訊,故此須要reduxjson

須要安裝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 有:

    1. PropTypes.array
    2. PropTypes.bool
    3. PropTypes.func
    4. PropTypes.number
    5. PropTypes.object
    6. PropTypes.string
    7. PropTypes.node,// 字符串,DOM 元素或包含這些類型的數組。
    8. PropTypes.element// React 元素
    9. PropTypes.instanceOf(Message), // 用 JS 的 instanceof 操做符聲明 prop 爲類的實例。
    10. PropTypes.oneOf(['News''Photos']), // 用 enum 來限制 prop 只接受指定的值。
    11. PropTypes.oneOfType([ PropTypes.stringPropTypes.numberPropTypes.instanceOf(Message]), // 指定的多個對象類型中的一個
    12. PropTypes.arrayOf(PropTypes.number),// 指定類型組成的數組
    13. PropTypes.objectOf(PropTypes.number),  // 指定類型的屬性構成的對象
    14. PropTypes.shape({ colorPropTypes.stringfontSize:PropTypes.number }), // 特定形狀參數的對象
    15. PropTypes.func.isRequired// 不可空的任意類型
    16. PropTypes.any.isRequired,// 之後任意類型加上 `isRequired` 來使 prop 不可空。
    17. customPropfunction(propspropNamecomponentNameif (!/matchme/.test(props[propName])) return new Error('Validation failed!'); },// 自定義驗證器。若是驗證失敗須要返回一個 Error 對象。不要直接 // 使用 `console.warn` 或拋異常,由於這樣 `oneOfType` 會失效。
相關文章
相關標籤/搜索