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特點
宣告式設計: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 處理
| |-components //元件 存放 React 元件,一般是該專案公用的無狀態元件
| |-containers //頁面檢視
| |-routes //路由 存放需要 connect model 的路由元件
| |-App.js //入口檔案
| |-index //註冊路由與服務
| |- serviceWorker //開發配置
|-package.json //包管理程式碼
|-.gitignore //Git忽略檔案
三,常用整合與配置
3.1,路由整合與配置使用
React Router 是一個基於 React 之上的強大路由庫,它可以讓你嚮應用中快速地新增檢視和資料流,同時保持頁面與 URL 間的同步。react-router
1 npm install [email protected] --save
Router下面只能包含一個盒子標籤,類似這裡的div。
Link代表一個連結,在html介面中會解析成a標籤。作為一個連結,必須有一個to屬性,代表連結地址。這個連結地址是一個相對路徑。
Route,是下面要說的元件,有一個path屬性和一個元件屬性(可以是component、render等等)。
複製程式碼
1 render(){
2 return (
3
4
5
- 首頁
- 其他頁
6
7
8
9
10
11
12
13 )
14 }
複製程式碼
路由支援巢狀,程式碼如下:
複製程式碼
1 const Root = () => (
2
3
4 <Route
5 path="/"
6 render={props => (
7
8
9
10
11
12
13 {/ 路由不正確時,預設跳回home頁面/}
14 <Route render={() => } />
15
16
17 )}
18 />
19
20
21 );
22
23 export default Root;
複製程式碼
3.2,redux整合與配置使用
React是單向資料流,所以有些情況下單單依賴React自身無法實現元件之間的通訊,故此需要redux
需要安裝Redux相關依賴,由於不同版本之間可能存在相容性問題,所以安裝的時候最好制定版本:
1 npm install [email protected] --save
2 npm install [email protected] --save
3 npm install [email protected] --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
21
{title}
22
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
會失效。
瀋陽胃腸醫院:jbk.39.net/yiyuanzaixian/shxkwckyy/
瀋陽胃腸醫院哪家:jbk.39.net/yiyuanzaixian/shxkwckyy/
煙臺胃腸醫院:jbk.39.net/yiyuanzaixian/ezamyy/
煙臺胃腸醫院哪家:jbk.39.net/yiyuanzaixian/ezamyy/