以前的 multi-spa-webpack-cli
只是爲 React + antd 模板提供了開發時必要的環境,對於實際的開發並無什麼用處。
爲了更貼近實際開發,本次 React + antd 模板完善了一些功能。node
node 服務和 React+antd 模板是沒有多大的關係的。本文只是想經過一個簡單的登錄邏輯來演示以上的功能,因此 node 服務不是必須的。react
multi-spa-webpack-cli
已經發布到 npm,只要在 node 環境下安裝便可。webpack
npm install multi-spa-webpack-cli -g
使用步驟以下:web
# 1. 初始化項目 multi-spa-webpack-cli init spa-project
<center>npm
</center>json
# 2. 進入文件目錄 cd spa-project # 3. 安裝依賴 npm install # 4. 打包不變的部分 npm run build:dll # 5. 啓動項目(手動打開瀏覽器:localhost:8090) npm start # 6. 啓動服務(可選) cd server npm install npm start
預覽:redux
<center>瀏覽器
</center>session
如今處理異步的方式,大多數基於 Promise 的。而 fetch 是自然支持 Promise 的,因此無需再手動封裝。在 PWA 技術中,已做爲一個重要的組成部分在使用。antd
fetch 爲人詬病的缺點之一,就是不能 Abort 請求。有方案提出提出,經過 Promise.race 的方法來模擬 timeout。實際上該執行的已然執行,只是表象上達到了預期的效果。不過瀏覽器現以實驗性開始支持 AbortController 。
import { notification } from 'antd'; const env = process.env.NODE_ENV; const baseURL = APP_CONFIG[env].ip; // timeout ; // const controller = new AbortController(); // const signal = controller.signal; const defaultConfig = { credentials: 'include', headers: { Accept: 'application/json' }, // signal }; const codeMessage = { 301: '永久移動', 302: '臨時移動', // ... 504: '網關超時。' }; const checkStatus = response => { if (response.status >= 200 && response.status < 300) { return response; } const errortext = codeMessage[response.status] || response.statusText; notification.error({ message: `請求錯誤 ${response.status}: ${response.url}`, description: errortext }); }; export default async function Fetch(url, config) { let newUrl = baseURL + url; let newConfig = { ...defaultConfig, ...config }; // const timeoutId = setTimeout(() => controller.abort(), 5000); if ( newConfig.method.toLocaleLowerCase() === 'post' || newConfig.method.toLocaleLowerCase() === 'put' || newConfig.method.toLocaleLowerCase() === 'delete' ) { if (!(newConfig.body instanceof FormData)) { newConfig.headers['Content-Type'] = 'application/json; charset=utf-8'; newConfig.body = JSON.stringify(newConfig.body); } } try { const response = await fetch(newUrl, newConfig); // clearTimeout(timeoutId); return checkStatus(response).json(); } catch (error) { notification.error({ message: `請求錯誤 : ${newUrl}`, description: error.message }); throw error; } }
自 raect-router v4 以後,便再也不支持集中式管理路由,不過也能夠本身手動去實現。React + antd 模板採用的是官網推薦的方式,layouts 目錄下的文件用來管理路由。
<center>
</center>
Redux 做爲狀態管理工具,除了 React,也能夠用在其餘地方(意思是說,和 React 沒半毛錢關係)。在React中使用時,咱們須要藉助 React-redux 工具,這樣使用起來更加方便。
嚴格的單向數據流是 Redux 架構的設計核心。
redux 數據流向:
就是把 action(行爲) dispatch(丟給)reducer(更新 state)。
<center>
</center>
node 服務登錄採用的是 session 來記錄狀態。
<center>
</center>
就這樣,一個簡單的腳手架宣告完成。
不過,這才只是個開始。