以前的 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
复制代码
# 2. 进入文件目录
cd spa-project
# 3. 打包不变的部分
npm run build:dll
# 4. 启动项目(手动打开浏览器:localhost:8090)
npm start
# 5. 启动服务(可选)
cd server
npm install
npm start
复制代码
预览:npm
如今处理异步的方式,大多数基于 Promise 的。而 fetch 是自然支持 Promise 的,因此无需再手动封装。在 PWA 技术中,已做为一个重要的组成部分在使用。json
fetch 为人诟病的缺点之一,就是不能 Abort 请求。有方案提出提出,经过 Promise.race 的方法来模拟 timeout。实际上该执行的已然执行,只是表象上达到了预期的效果。不过浏览器现以实验性开始支持 AbortController 。redux
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 目录下的文件用来管理路由。浏览器
Redux 做为状态管理工具,除了 React,也能够用在其余地方(意思是说,和 React 没半毛钱关系)。在React中使用时,咱们须要借助 React-redux 工具,这样使用起来更加方便。bash
严格的单向数据流是 Redux 架构的设计核心。session
redux 数据流向:
就是把 action(行为) dispatch(丢给)reducer(更新 state)。
node 服务登录采用的是 session 来记录状态。
就这样,一个简单的脚手架宣告完成。
不过,这才只是个开始。