写法不同,思路相同
模块化
避免超长 import 引入
思路:从模块入口文件(如index.ts)导出,避免代码可读性差等问题。
// 原例
import A from '@/services/a';
import B from '@/services/b';
import C from '@/services/c';
import D from '@/services/d';
import E from '@/services/e';
import F from '@/services/f';
import G from '@/services/g';
// import ...
👇👇👇
// services/user/index.ts
export const login: API.User.loginFn = request('http://xxxxx');
export const logout: API.User.logoutFn = request('http://xxxxx');
// services/index.ts
export default {
...(await import('@/services/user')),
...(await import('@/services/post')),
};
import { A, B, C, D, E, F, G } from '@/services';
// ts 同理
declare namespace API {
// code ...
}
嵌套
异步嵌套
思路:各大语言 async/await 语法糖。
// 经典 then 嵌套回调地狱
promise.then().then().then().then();
// 业务代码忽略
👇👇👇
await promise();
await promise();
await promise();
await promise();
// 业务代码忽略
if/switch 代码块嵌套
思路:拆分判断。
// 原例
try{
if () {
// code ...
} else if () {
// code ...
} else if () {
// code ...
}
else{
// code ...
}
}
catch{
// code ...
}
👇👇👇
// try catch 通过统一封装的 请求 或 拦截器 处理异常
// 处理嵌套 if
const getUser = () => {};
const getPost = () => {};
const fn = () => {
flag && getUser();
flag && getPost();
};
数据嵌套
思路:状态提取。
// 原例
const ComponentA = (params) => {
params.user = currentUser;
return <ComponentB {...params} />;
};
const ComponentB = (params) => {
params.user = 'xxx'; // js 弱语言赋值
return <ComponentC {...params} />;
};
const ComponentC = (params) => {
params.user = false; // js 弱语言赋值
return <ComponentD {...params} />;
};
const ComponentD = (params) => {
return <div>{params.user.name}</div>; // ?。。。
};
👇👇👇
// xxxstore.ts
// 创建 store 可参考 redux mobx vuex getx 等状态库
// store + ts
// 简单示例
const ComponentA = (params) => {
store.changeUser();
return <ComponentB />;
};
const ComponentB = (params) => {
store.changeUser();
return <ComponentC />;
};
const ComponentC = (params) => {
store.changeUser();
return <ComponentD />;
};
const ComponentD = (params) => {
return <div>{params.user.name}</div>;
};
组件 or 函数 嵌套
思路:
组件 创建局部 store 提取状态,拆分各组件,组件订阅状态(同理解决 flutter 嵌套)。
函数 拆分各函数功能,提高复用性,阅读性,避免过渡拆分与不拆分(大师我悟了)。
// 原例
const xxTable = () => {
return (
<>
{
// search bar > input > button
// form > list
// drawer > detail
}
</>
);
};
// 避免一个组件几千行代码n种组件状态
👇👇👇
// xxTableStore.ts
// store ...
// xxTable
const xxTable = () => {
return (
<>
<Search />
<Form />
<Drawer />
</>
);
};
开发规范
思路:通过eslint、stylelint、commitlint、命名规范等约束开发人员
// 原例
var u = {name:'',password:''};// 变量提升,缩写命名
class="selectbox1"
git commit -m "人间正道是沧桑"
git commit -m "大师我悟了"
👇👇👇
const user = {name:'',password:''};
class="select-box"
.select-box:nth(1){}
git commit -m "feat: your message"
git commit -m "fix: your message"
项目原则
🎯不要敏捷开发(共同确认需求)
🎯需求变更留痕(避免相互甩锅)
🎯规范项目排期(过滤开发重点)